How can I preserve current SPA route upon page refresh?

I've got an app nearly up and running. I've configured all the state with context API, created all the backend routes and the frontend routes. The data is fetched from the API no problems. Login routes the user to the right destination and so does logging out.

However, when I refresh a page on any given page, the route follows my private route. Here's the code for it as it's a separate component:

export const PrivateRoute = ({ component: Component, ...rest }) => {
  const authContext = useContext(AuthContext);
  const { isAuthenticated } = authContext;

  return (
    <Route { ...rest } render={props => !isAuthenticated ? (
        <Redirect to='/login' />
      ) : (
        <Component {...props} />
      )} 
    />
  )
}

My routes on the front end are as follows:

<Switch>
  <Route exact path='/login' component={Login} />
  <PrivateRoute exact path='/' component={Main} />
  <PrivateRoute exact path='/events' component={EventsPage} />
  <PrivateRoute exact path='/keywords' component={Keywords}/>
  <PrivateRoute exact path='/register' component={Register} />
</Switch>

When the user is authenticated and in events, for example, they can see the content. When they refresh, the route goes back to the Login page (as it should) and then re-directs the user back to the main page, at '/' (as it should).

However, I want the page to stay on Events when it refreshes.

I've read about having routes configured correctly on both the backend as well as the front end but not sure how to implement as everything works fine other than this.

Answers:

Answer

My guess without seeing the rest of your code would be that you are storing the information that decides whether or not a user is authenticated in state that resets on refresh rather than something that persists on reload like session storage, local storage or cookie.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.