abbey
abbey

Reputation: 223

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.

Upvotes: 9

Views: 11313

Answers (4)

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20088

We can sync the logout and login functionality in the following way

    useEffect(() => {
        let timeout
        const handleInvalidToken = () => {
            // help us to logout current and other tabs
            if (localStorage.getItem('token') === null && authentication.authenticated) {
                window.location.assign('/')
            }
            // help us to login current and other tabs
            if (localStorage.getItem('token') !== null && !authentication.authenticated) {
                timeout = setTimeout(() => window.location.assign('/'), 1000)
            }
        }
        window.addEventListener('storage', handleInvalidToken)
        return function cleanup() {
            window.removeEventListener('storage', handleInvalidToken)
            clearTimeout(timeout)
        }
    })

Upvotes: 0

HelloAmarnath
HelloAmarnath

Reputation: 66

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
        };

Upvotes: 5

kostik
kostik

Reputation: 1209

You can use https://github.com/tejacques/crosstab or implement something like this by yourself

Upvotes: 0

Dobby Dimov
Dobby Dimov

Reputation: 1032

Add an event listener to track changes of the jwt in localStorage.

Example with useEffect:

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

    window.addEventListener('storage', handleInvalidToken)

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

Upvotes: 2

Related Questions