Skip to content
Advertisement

How to log out all tabs in one browser when one tab is logged out in React.js?

I’m new to React. I want to know how to auto log out all tabs in one browser when one tab is logged out in React.js.(not using redux) I use JWT and store JWT on local storage. Please any one help me on this. Thanks.

Advertisement

Answer

1) On Component mount write this code and call the action on addEventListener when token is removed from the storage

    useEffect(() => {
    const handleInvalidToken = e => {
      if (e.key === 'token' && e.oldValue && !e.newValue) {
        // Your logout logic here

        console.log(e)
        logoutAction(history);

      }
    }
    window.addEventListener('storage', handleInvalidToken)
    return function cleanup() {
      window.removeEventListener('storage', handleInvalidToken)
    }
  }, [logoutAction])

2) In logout logoutAction will look like below – Redux Action

export const logoutAction = (history) => dispatch => {
  dispatch({ type: LOGOUT });
  history.push('/signin')
};

3) In Logout Reducer to be look like below code – Redux Reducer.

case LOGOUT:
        localStorage.removeItem('token');
        return {
          ...state,
          token: null,
          isAuthenticated: false,
          loading: false
        };
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement