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.
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.
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.
The most popular one that's used with React is redux. Redux is not shared across multiple tabs.
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With