i'm working on a MERNG app, and i have a problem loging out the user.
So, i have a route, that will take you to a page where the url has /profile/userId, the userID is given by the localStorage since i'm taking that value from there, and, when i logout i remove the token from the localStorage, so, if there's no values, it should take you login page.
Now, the problem is that, when i login, and get to the /profile/userId page, and i refresh the page with f5, if i logout, it won't let me do it, the redirecting doesn't work, it only works if i don't refresh the page, and that's a big issue for my app, and it's actually weird.
Maybe it's a problem with my code, i don't know that well how to use Redirect, so if you can help me with this, you're the greatest !
So this is the code
Routes with the redirect
import React from "react";
import "./App.css";
import {
BrowserRouter as Router,
Switch,
Route,
Redirect
} from "react-router-dom";
import Auth from "./website/Auth";
import SocialMedia from "./website/SocialMedia";
import SingleUser from "./website/SingleUser";
function App() {
const logIn = JSON.parse(localStorage.getItem("token"));
return (
<Router>
<Switch>
<Route exact path="/">
{logIn ? <Redirect to={`/profile/${logIn.data.id}`} /> : <Auth />}
</Route>
<Route exact path="/socialmedia" component={SocialMedia} />
<Route exact path="/profile/:id" component={SingleUser} />
</Switch>
</Router>
);
}
export default App;
To logout
import React from "react";
import { useHistory } from "react-router-dom";
import { useDispatch } from "react-redux";
const SingleUser = () => {
const history = useHistory();
const dispatch = useDispatch();
const userData = JSON.parse(localStorage.getItem("token"));
const logout = () => {
dispatch({ type: "LOGOUT" });
if (!userData) {
history.push("/");
}
};
return <div onClick={logout}>Single User</div>;
};
export default SingleUser;
My reducer where i store the token in the localStorage and remove it with logout action
const reducer = (state = { authData: null }, action) => {
switch (action.type) {
case "LOGIN":
localStorage.setItem("token", JSON.stringify({ data: action.payload }));
return {
...state,
authData: action.payload
};
case "LOGOUT":
localStorage.removeItem("token");
return {
...state,
authData: null
};
default:
return state;
}
};
export default reducer;