Home > front end >  On React Router, stay on the same page even if refreshed
On React Router, stay on the same page even if refreshed

Time:05-30

my site is built using MERN stack, when I refresh a page it first shows the main page and then the page where the user is. How to fix this issue? For example:

if I refresh (/profile) page then for a meanwhile it shows (/) then it redirects to (/profile). I want if I refresh (/profile) it should be on the same page.

import { Route, Redirect } from 'react-router-dom';
const PrivateRoute = ({ component: Component, authed, ...rest }) => {
   
    return (
        <Route
            {...rest}
            render={(props) => authed === true
                ? <Component {...props} />
                : <Redirect to={{ pathname: '/', state: { from: props.location } }} />}
        />
    )
}

export default PrivateRoute;

Router code:

const App = () => {
  const user = useSelector((state) => state?.auth);

  return (
    <>
    
    <BrowserRouter>
      <Container maxWidth="lg">
        
        <Switch>
          <Route path="/" exact component={Home} />
          
          <Route path="/about" exact component={About} />
          <Route path="/terms" exact component={Terms} />
        
          <PrivateRoute authed={user?.authenticated} path='/profile' component={Profile} />
         
        </Switch>
      
      </Container>
     
    </BrowserRouter>
   
   
 </>
  )
}

export default App;

How to fix so that user stays on the same page if its refreshed? The issue is on the pages where authentication is required.

CodePudding user response:

I guess on mounting (=first render) your user variable is empty. Then something asynchronous happen and you receive a new value for it, which leads to new evaluation of {user?.authenticated} resulting in true and causing a redirect to your /profile page.

I must say I'm not familiar with Redux (I see useSelector in your code, so I assume you are using a Redux store), but if you want to avoid such behaviour you need to retrieve the right user value on mounting OR only render route components when you've got it later.

  • Related