I have this component NotificationToast that manages notifications.
I need to be always rendered when the user is authenticated.
So this is what I did:
class App extends Component {
render() {
const state = store.getState();
const { isAuthenticated } = state.auth;
return (
<Provider store={store}>
<BrowserRouter basename="/">
<Switch>
<PublicRoute path="/register-page" component={RegisterPage} />
<PrivateRoute path="/profile-page" component={ProfilePage} />
<Redirect to="/home" />
</Switch>
{isAuthenticated && (
<div>
<NotificationToast />
</div>
)}
</BrowserRouter>
</Provider>
);
}
}
export default App;
The problem is that this does not work in the following scenario:
state.auth.isAuthenticated is falsestate.auth.isAuthenticated gets set to true.App does not detect this change and so it does not get rerendered.NotificationToast does not get rendered.This works when the user refreshes the page after he logs-in, because state.auth.isAuthenticated is true from the beginning.
This is because of this code:
if (localStorage.jwtToken) {
// Set auth token header auth
setAuthToken(localStorage.jwtToken);
// Decode token and get user info and expiration
const decoded = jwt_decode(localStorage.jwtToken);
// Set User and is Authenticated
store.dispatch(setCurrentUser(decoded));
// Now if you reload a page, if the user has already logged-in you will still have his info in he state
store.dispatch(clearCurrentProfile());
// Check for expired token
const currentTime = Date.now() / 1000;
if (decoded.exp < currentTime) {
store.dispatch(logoutUser());
store.dispatch(clearCurrentProfile());
// Redirect to login
window.location.href = "/login";
}
}
It checks if the user has already logged-in, and if he did it sets state.auth.isAuthenticated to true.
Any suggestions?
useStore is used to retrieve store. But such store access can only be used for store manipulation, like reducer replacement. When store is changed, component which access store this way is not updated.
Please use "useSelector"
const isAuthenticated = useSelector(state => state.auth)