Setting data in React for useContext

85 Views Asked by At

could you please help with setting state in useContext ? I am trying to send video variable through useEffect to setMediaContent to update mediaContext.media object. My goal is to have several media(video,images,posters) objects in media object, e.g.

https://codesandbox.io/s/friendly-sunset-o67nvj?file=/src/context.js

Thanks in advance

2

There are 2 best solutions below

0
Saul Ramirez On

Try using a reducer:

import { createContext, useReducer } from "react";

// default state
const contextDefaultValues = {
  video: { url: "", title: "", shown: false },
  openVideo: () => {},
  closeVideo: () => {},
  mediaContent: { media: {}, title: "most" },
  setMediaContent: () => {},
};

const MainReducer = (state = contextDefaultValues, action) => {
  const { type, payload } = action;
  switch (type) {
    case "setMediaContent": {
      const { media, title } = payload;
      return { ...state, media: { ...state.media, ...media }, title: title };
    }
    case "closeVideo": {
      return { ...state, shown: false };
    }
    case "openVideo": {
      const { url, title } = payload;
      return { ...state, url, title, shown: true };
    }
    default: {
      throw new Error(`Unhandled action type: ${type}`);
    }
  }
};

export const MainContext = createContext(contextDefaultValues);

// provider recuder
const MainProvider = ({ children }) => {
  const [state, dispatch] = useReducer(MainReducer, contextDefaultValues);

  const openVideo = (url, title) => {
    dispatch({ type: "openVideo", payload: { url, title, shown: true } });
  };

  const closeVideo = () => {
    dispatch({ type: "closeVideo", payload: { shown: false } });
  };

  const setMediaContent = (media, title) => {
    dispatch({ type: "setMediaContent", payload: { media, title } });
  };

  return (
    <MainContext.Provider
      value={{ ...state, setMediaContent, closeVideo, openVideo }}
    >
      {children}
    </MainContext.Provider>
  );
};

export default MainProvider;

0
Eghizio On

Based on the provided sandbox, You have the render of the provider wrapped in the setMediaContent function.

Look at the { and } at line 36 and 58.

Code screenshot with misplaced brackets