The app should redirect to /dashboard when user is not null. User is null in the first render but useEffect() should pick up and store user data from local storage. Then, the ternary operator should trigger <Redirect to='/dashboard' /> and redirects to dashboard page. But, it's not doing that. It just keeps showing the login page at /login whenever I refresh even if there is data in localStorage.
What am I doing wrong or how can I solve this?
const App = () => {
const [user, setUser] = useState(null)
useEffect(() => {
const loggedUserJSON = window.localStorage.getItem('loggedUser')
if (loggedUserJSON) {
const user = JSON.parse(loggedUserJSON)
setUser(user)
noteService.setToken(user.token)
}
}, [])
return (
<Router>
<Switch>
<Route exact path='/'>
{user
? <Redirect to='/dashboard' />
: <Redirect to='/login' />
}
</Route>
<Route exact path='/login'>
<LogIn />
</Route>
<Route exact path='/dashboard'>
<Dashboard />
</Route>
</Switch>
</Router>
)