I'm keeping my user session in a redux state.
I have a login reducer with the initialState below
const initialState = {
logged: false,
user: null,
}
After login, I set the logged to true and the user details.
Then, I have a Navigation folder using react-router-dom to manage my navigation with a PrivateRoute function to validate if user is logged.
const PrivateRoute = ({ component, ...options }) => {
const login = useSelector((state) => state.login);
console.log(login);
const finalComponent = login.logged ? component : Login;
return <Route {...options} component={finalComponent} />;
};
const Navigation = () => {
return (
<Router>
<Switch>
<PrivateRoute exact path="/" component={Home} />
<Route exact path="/login" component={Login} />
<PrivateRoute exact path="/checkRegister" component={CheckRegister} />
</Switch>
</Router>
)
}
export default Navigation;
Everything works just fine if I open the application login and start to navigate. However, if I refresh the browser or, after login, change the browser from localhost:3000/ to localhost:3000/checkRegister it kills the state and return to the login page because the state login.logged is back to the initial value which is false.