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.
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.
Share Improve this question asked Nov 17, 2018 at 15:17 abbeyabbey 2233 gold badges8 silver badges17 bronze badges 3- 1 Build something that polls the token state in localstorage – Jonathan Commented Nov 17, 2018 at 15:21
- Please show what you have tried so far. – Paul Commented Nov 17, 2018 at 15:22
- Do you want to send the user to the login page on tab-1, when you logout from tab-2 ? – umki Commented Nov 19, 2018 at 10:57
4 Answers
Reset to default 51) 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
};
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])
You can use https://github./tejacques/crosstab or implement something like this by yourself
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)
}
})