I have a React/Node application which let the user login and get redirected to his dashboard. What I want to achieve is to prevent the user from going to the other pages if he is not logged in. My App.js looks like this :
function App() {
const userInfo = localStorage.getItem("userInfo");
let resultat = JSON.parse(userInfo);
if(resultat!==null){
if(resultat.status==="ok"){
return (
<>
<Router basename={process.env.PUBLIC_URL}>
<Switch>
<Route path='/' exact component={ Dashboard }>
</Route>
<Route path='/login' exact component={ Login }>
</Route>
<Route path='/dashboard' exact component={ Dashboard }>
</Route>
<Route path='/other_route' exact component={ OtherComponent }>
</Route>
</Switch>
</Router>
</>
);
} else {
return(
<>
<Router basename={process.env.PUBLIC_URL}>
<Switch>
<Route path='/' exact component={ Login }>
</Route>
<Route path='/login' exact component={ Login }>
</Route>
<Route path='/*' exact>
<>
You are not logged in. To see this page please, log in.
</>
</Route>
</Switch>
</Router>
</>
);
}
} else {
return(
<>
<Router basename={process.env.PUBLIC_URL}>
<Switch>
<Route path='/' exact component={ Login }>
</Route>
<Route path='/login' exact component={ Login }>
</Route>
<Route path='/*' exact>
<>
You are not logged in. To see this page please, log in.
</>
</Route>
</Switch>
</Router>
</>
);
}
}
My Login.js component redirects the user to the path /dashboard
if the login process is successful.
The problem is that it still loads the page that says to go to the login. If I reload the page though, it shows the actual dashboard.
I happens because (I guess) React just switches between the routes, from /login
to /*
(/dashboard
) but it doesn't rerun the App()
function so it can't redo the if(resultat!==null)
test.
I figured that if I tried to force React to reload the page while going to the dashboard (I tried this answer) but it didn't work.
Is there any way to achieve what I want to do ?
Thanks in advance.