#React Router - Context issue

9 messages · Page 1 of 1 (latest)

viscid pond
#

So are not able to access the values of useContext in the component ?
can you try to wrap your App with context provider instead?

wraith rampart
#

Tried also that but didn't work.

viscid pond
#

Okay so can you clarify what do you mean by

useContext is not working in child components.
Are you able to read the context values in the child components?

what is the QueryClientProvider ? is that another context?

#

If so, can you disable that and check if your routes are able to then access your LicContext values?

The thing with useContext is that it always looks for the closet provider above the component that calls it.
So it might be that you just need to wrap each element with Context you need to pass as the useContext in each Route ends up looking for provider in Routes.
so maybe also try this

<Route path="/logout" element={
  <LicContext.Provider value={{ admin, setAdmin, loggedIn, setLoggedIn}}>
      <Logout />
  </LicContext.Provider>
} 
/>
#

might not be the best way but for now lets troubleshoot to know if this is the problem or not

wraith rampart
#

I try to clarify, useContext part means that when I move to another component via router then state in context provider gets default value ex. admin state get's false, which in practice means that
there is no more admin menu visible.

Use case: One logging with admin account and navibar start to show correctly admin and action menu. You then select show licenses via Action menu and then you don't anymore have admin menu visible due to reason that license component read useContext admin state and it's false. This make me think that useContext is not compatible with router usage.

QueryClientProvider doesn't impact to this at all so need to worry from it.

And yes, I have checked multiple times with console.log 🙂

viscid pond
twilit narwhal
#

The easiest solution I can think of is to have an admin property on the user and then check for it when rendering admin components

wraith rampart
#

Hmm user has admin property... I recheck my code and when login in with the admin account admin state in the login component is true (as it should). Additionally, I'm storing admin value to the sessionStorage. So I'm logging in with an admin account and based on alert Navbar and other components and so the admin value as empty? Currently still trying to change the admin state with useContext hook, but doesn't seem to work. Navbar is there from the start so cannot imho just send admin property from Login to Navbar as then Navbar would be shown double. I would like to keep my Router system in place so if you guys can advise with an example / point me to some nice youtube clip that would be excellent.