'ReactJs: How to make root component rerender when a prop changes

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:

  1. The user has not logged-in.
  2. So he is not authenticated. So state.auth.isAuthenticated is false
  3. When he logs-in, state.auth.isAuthenticated gets set to true.
  4. But, the problem is that App does not detect this change and so it does not get rerendered.
  5. And so, NotificationToast does not get rendered.
  6. And so the notification system doesn't work.

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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source