I am new to React. When the user clicks on logout button the context function logout calls and delete the localStorage token and empty all the variables. For a split second the variables do get empty but then again they get filled. I checked my logout function and I cant see any bug to find. the localStorage is destroying perfectly but other state variables are not erasing.
AuthState.js
// Load User
const loadUser = async () => {
if(localStorage.token) {
setAuthToken(localStorage.token);
}
try {
const res = await axios.get('/api/auth');
dispatch({
type: USER_LOADED,
payload: res.data
});
loadUser();
} catch (err) {
dispatch({type: AUTH_ERROR});
}
}
// Logout User
const logout = () => dispatch({type: LOGOUT});
authReducer.js
case LOGOUT:
localStorage.removeItem('token');
return {
...state,
token: null,
isAuthenticated: false,
loading: false,
user: null,
error: action.payload
}
Navbar.js
export const Navbar = ({ title, icon }) => {
const authContext = useContext(AuthContext);
const { isAuthenticated, user, logout } = authContext;
const onLogout = () => {
logout();
console.log('user');
console.log(user);
};
const authLinks = (
<Fragment>
<li>
Hello {user && user.name}
</li>
<li>
<a onClick={onLogout} href="#!">
<i className="fas fa-sign-out-alt" /> <span className="hide-sm">Logout</span>
</a>
</li>
</Fragment>
)
const guestLinks = (
<Fragment>
<li>
<Link to="/register">Register</Link>
</li>
<li>
<Link to="/login">Login</Link>
</li>
</Fragment>
)
return (
<div className="navbar bg-primary">
<h1>
<i className={ icon } /> <Link to="/">{ title }</Link>
</h1>
<ul>
{isAuthenticated ? authLinks : guestLinks}
</ul>
</div>
)
}
after clicking on logout button every value comes back but token is deleted perfectly. Screenshot below
It worked now. I guess all I needed to do was remove if block from setAuthToken in loadUser().