Home > database >  React js context api is not woking how to fix it?
React js context api is not woking how to fix it?

Time:03-18

I'm was making the shopping card Project and I decide to use Contextapi and useReducer for my state management at the start of my project I wrap the App in context Api and it crash my App Here is the Code.

****Main Index *******

    import React from "react";
    import ReactDOM from "react-dom";
    import "./index.css";
    import App from "./App";
    import Context from "./Context";

    ReactDOM.render(
     <React.StrictMode>
      <Context>
      <App />
    </Context>   </React.StrictMode>,
   document.getElementById("root")
  );

**** Context Api******

import { createContext } from "react";
const Card = createContext();
const Context = ({ childern }) => {
  return <Card.Provider>{childern}</Card.Provider>;
};

    export default Context;

CodePudding user response:

Just a guess because you didn't provide enough information on the error but you could try moving the context initialization to a separate module and just import it where you need it.

I ran into a strange runtime issue when I initialized it in a UI component.

CodePudding user response:

You need to pass a value prop to context provider without that there is no point of using context API.

As you have mentioned you are using useReducer , an example would be like below to pass the state to the children.

const Context = ({ childern }) => {
  const [state,dispatch] = useReducer(reducer,initialState)
  return <Card.Provider value={state}>{childern}</Card.Provider>;
};
  • Related