Home > database >  React Context Value always returning undefined
React Context Value always returning undefined

Time:01-24

I am new to working with contexts and I'm just trying to start slow. I saw a thing about logging your Provider to test the value and I am getting a constant undefined value. I have moved them right next to each other in the code to see if that changes anything.

const PromptContext = createContext('test123');
function generateRecipe() {
    <PromptContext.Provider value="hello">xxx</PromptContext.Provider>
    console.log(PromptContext.Provider.value);
    console.log("Generating recipe...");
  }
}

Upon this function being called the log value is always undefined, no matter what is put in the value of the Provider. Any ideas on fixing this?

The end goal is to get the value of the provider into this consumer which is in a separate react file

<PromptContext.Consumer>
    {test => (
        <h1>{test.value}</h1>
    )}
</PromptContext.Consumer>

CodePudding user response:

Your provider should not be part of a function (in the way you have it listed, anyway). The provider, of course, WILL be a function, but you aren't going to just be including it inside functions in the same way you showed above. It's actually easier than that!

You want it like this:

export const PromptContext = createContext();

export const PromptContextProvider = ({children}) => {
  // All of your logic here
  const baseValue = 'hello';

  return (
    <PromptContext.Provider value={{baseValue}}>
      {children}
    </PromptContext.Provider>
  )
}

You don't mix the provider with your end function like you're doing above.

Instead, in your index.js file, you'll wrap your component:

root.render(
  <PromptContextProvider>
    <App />
  </PromptContextProvider>
)

And then you can access your baseValue by using const {baseValue} = useContext(PromptContext) in your components.

CodePudding user response:

Edit bold-margulis-uh1by8

  • Related