Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 841
abbey Avatar asked Nov 17 '18 15:11

abbey


People also ask

How user will logout from all open tabs automatically when user logs out in one of them?

setItem('logout-event', 'logout' + Math. random()); Every other tab will get it with a listener. You can use both approaches - localStorage and auto-refresh, for example every 60 seconds, just to be sure it works when tabs are opened at different computers.

How do you handle the user logout in browser multiple tab react?

There is a neat little way to log out all the tabs if the user clicks logout from one tab. Since we will be maintaining a token in localStorage. We can add an event listener for our storage and check if the token becomes null then, we'll dispatch a logout action to logout the user from all the open tabs.

Is react state shared between tabs?

The most popular one that's used with React is redux. Redux is not shared across multiple tabs.


1 Answers

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
        };
like image 71
HelloAmarnath Avatar answered Nov 14 '22 23:11

HelloAmarnath