2

I am using useContext hook to sore the state to check if user loggedin or not and using protectedRoutes to protect my pages from access. But after login, if i reload/refresh any of the proteted page, it again takes me to the login screen. WHY?

const [userstate, dispatch] = useReducer(reducer, initialvalue)
return (
<>
<Mycontext.Provider value={{userstate, dispatch}}>
<Routes>
  <Route path = "login" element = {<Login/>} />
   <Route path = "/" element = {<ProtectedRoutes />}>
     <Route path="/" element={<dashboard />} />
     <Route path="welcome" element={<dashboard />} />
     <Route path="page1" element={<page1 />} />
     <Route path="page2" element={<page2 />} />
   </Route>
  <Route path = "*" element = {<Error/>} />
</Routes>
</Mycontext.Provider>

I am using dispatch in the login and logout buttons to set state true or false in the reducer with payload. How can I solve this, give some solution on this.

  • You can't persist the data on a state on page refresh, so that's a normal behaviour. If you want to persist user's info you could use local storage/session storage/cookies and retrieve the data from there. – ivanatias Jul 02 '22 at 04:41
  • You can also use some redux middleware to achieve this. https://stackoverflow.com/questions/37195590/how-can-i-persist-redux-state-tree-on-refresh – ParagDineshGupta Jul 02 '22 at 04:48
  • thanks, i think localStorage/cookies is the right option – viru jamwal Jul 04 '22 at 06:27

0 Answers0