This is my primary react file:
// App.tsx
const App: FC = () => {
const isLoggedIn: boolean = localStorage.getItem('logged_user') !== null;
return (
<BrowserRouter>
<Routes>
<Route path="/main" element={isLoggedIn ? <Main/> : <Navigate to='/login'/>}/>
<Route path="/about" element={isLoggedIn ? <About/> : <Navigate to='/login'/>}/>
<Route path="/login" element={<Login/>}/>
</Routes>
</BrowserRouter>
);
}
export default App;
After logging in, I store the user in local storage.
I want to achieve the behaviour of redirections to the /login page when the user is not authenticated (when it is not stored in localstorage).
Generally, the above approach works but only sometimes. Sometimes, when I go to ‘/main’, I would get redirected to ‘/login’ even though I was logged in. I assume this is caused by React’s nature of re-renders.
How can I approach this?