-2

I am using useContext to pass the account name to all the pages that I have created in app.js.

contextProvider.jsx

import { createContext, useState } from 'react';

export const LoginContext = createContext(null);

const ContextProvider = ({children}) => {

    const [ account, setAccount ] = useState('');
    
    return (
        <LoginContext.Provider value={{ account, setAccount }}>
            {children}
        </LoginContext.Provider>
    )
}

export default ContextProvider;

Now I am using it in app.js for making it available for all pages.

app.js

import ContextProvider from './context/ContextProvider';
export default function app(){
return (
    <ContextProvider>
       <BrowserRouter>
          <Routes>
              {/* home page where i changing the account value. My header component is wrapped inside this MainPage-component */}
              <Route exact path='/home-services' element={<HouseDeckHomeServicesMainPage city={city} setCity={setCity} handleData={handleData} />} />

              <Route exact path='/home-services/about-us' element={<HouseDeckHomeServicesAnotherPage />} />
      
           </Routes>
       </BrowserRouter>
    </ContextProvider>
  );

}

Then I recalling the variables in LoginContext from contextProvider.jsx to change or set them to a partcular value.

Header.jsx

export default function Header(){
const {account, setAccount} = React.useContext(LoginContext)
// let I am doing in header.jsx
setAccount("hello")
return (
   <div>{account}</div>
)

}

Suppose i am doing setAccount("Hello") in my Header.jsx to change it. The LoginContext variable account changed. I checked by printing it.

Now I want to use the same value that I stored in account in other pages.

I don't know how to use that value.

Right now I am doing

AnotherPage.jsx

export default function AnotherPage() {
    const {account} = React.useContext(LoginContext)
    // I want to print the value of account that i changed from 
    // null to "hello" in this page but i am getting undefined 
    // here.
    console.log(account)
    return (
        <div>{account}</div>
    )
}

But it is taking the default value of account that is null which is not what I want. I want to use the changed value. Please help.

Yash-Sharma2002
  • 89
  • 1
  • 10
  • 1
    If `Content` component is receiving a null context value then it seems it is being rendered ***outside*** the `ContextProvider` component. Please update your question to include properly formatted and readable code snippets instead of images. – Drew Reese Mar 17 '22 at 07:47
  • **Context** is receiving its value as I said in the question. I think you haven't read the question properly, please read it line by line you will understand what I am saying. I am saying it again "I want to use the value of assigned context variable **account** in other components too as I posted in app.js but I don't know how to declare and use them as I showed in AnotherPage.jsx . " – Yash-Sharma2002 Mar 17 '22 at 07:57
  • I don't think you've quite grasped the concept of Context API. Kindly refer to the [official Context API docs](https://reactjs.org/docs/context.html). I'm sure you'll solve your problem. – Batman Mar 17 '22 at 07:59
  • Also, why are you setting your initial `account` state to be the `LoginContext` Context itself? Please do try to update your question to include [full and complete, reproducible code](https://stackoverflow.com/help/minimal-reproducible-example). – Drew Reese Mar 17 '22 at 08:03
  • I used it as ** "" ** initially but it was not working, So, I searched for it and get that answer but it was not correct. – Yash-Sharma2002 Mar 17 '22 at 08:05
  • here the updated code and its not working too. – Yash-Sharma2002 Mar 17 '22 at 08:25
  • I am unable to reproduce the issue you describe here in this minimal, running [codesandbox](https://codesandbox.io/s/how-to-use-usecontext-changed-value-w0o7sf) demo. – Drew Reese Mar 17 '22 at 08:52
  • You are doing it correct. Please consider adding routes between components. It will help me a lot. My header component in wrapped in every routing component because it is dynamic. – Yash-Sharma2002 Mar 17 '22 at 08:55
  • That should make no difference, but for the sake of discussion, sure, I placed one of the components on a route. It still doesn't reproduce the issue as you describe. Perhaps you could provide a *running* codesandbox that *does* reproduce the issue that we could inspect and debug live? – Drew Reese Mar 17 '22 at 09:06
  • Wrap header into another component and use that function name instead of using header in app and then try it. I've done it and faced the error. – Yash-Sharma2002 Mar 17 '22 at 09:15
  • I'm telling you, it doesn't matter how deeply you nest `Header` or any other component, if they are both in the ReactSubTree of the the same `ContextProvider` component they will have access to the same context value. I've updated my CSB and it still works as I'd expect, without issue. – Drew Reese Mar 17 '22 at 09:19
  • I just tried in your sandbox bro. And I faced the error. – Yash-Sharma2002 Mar 17 '22 at 09:19
  • What are you doing differently then? ‍♂️ Please share a complete example for what you are doing that is producing any issues? Feel free to fork my sandbox, create the issue, save it, and share the link. – Drew Reese Mar 17 '22 at 09:21
  • Give me sometime – Yash-Sharma2002 Mar 17 '22 at 09:21
  • I tried and it's like sometimes works and sometimes not. – Yash-Sharma2002 Mar 17 '22 at 10:35

2 Answers2

0

You propably dont have your Header.jsx outside of you ContextProvider. Try to wrap whole App component in it instead of just routes

Wraithy
  • 1,722
  • 1
  • 5
  • 13
0

I've faced exactly your problem.

Time to use useMemo:

const dataMemo = useMemo(() => {
    return {
        account, setAccount
    }
}, [account, setAccount])

return <LoginContext.Provider value={dataMemo}>
    {children}
</LoginContext.Provider>

Don't forget import {useMemo} from 'react' on the top

Hope it can help ^^

mikenlanggio
  • 1,122
  • 1
  • 7
  • 27