1

I was trying to use useContext to change the authentication state when a user logs in and this would be received in other components to conditionally show based on whether the user has logged in.

Login Context was setup as below

Login Context

I passed the provider in this way

Provider

I made a button which upon clicking sets loggedIn as true

set login

However, when I re-route to store, the value from useContext still stays as false although I have updated it in the Login component

store consloe output

Upon routing back to "/login" the state from useContext still shows false rather than true

login rerender

Am I missing something wrt how useContext works?

akanxh2000
  • 79
  • 2
  • 8

2 Answers2

1

That's expected. You dispatch your action, but the resulting state will be visible only on the next render phase. Not immediately. It will not happen synchronously. If you want to inspect that value, you can:

React.useEffect(() => {
  console.log('loggedIn value changed', state.loggedIn)
}, [state.loggedIn])
Federkun
  • 36,084
  • 8
  • 78
  • 90
  • Yes, but upon routing to "/store", the value from the context is still false though I have set it to true in the Login Component. I have updated my answer to reflect the same. Could you help me out here? – akanxh2000 Jun 06 '21 at 04:13
  • Can you move the `LoginProvider` above `Switch`? – Jemy Jenesh Jun 06 '21 at 04:24
  • @JemyJenesh it did not change, upon routing to `"/store"` the value from the context was still `false` – akanxh2000 Jun 06 '21 at 04:45
0

I managed to figure out what was happening from another post: useContext does not survive between pages

So, by using react-router-dom and Link the application now works and passes the context to different pages and components but does not survive upon refresh or on opening a new tab.

answer

Note that if this feature is required, for example login/auth, the best way is through localStorage

akanxh2000
  • 79
  • 2
  • 8