Last active
July 28, 2022 03:33
-
-
Save paambaati/810ad1ddc530c6bc4b7b0b6fb9e4cec2 to your computer and use it in GitHub Desktop.
Logging out of all tabs when logout occurs on 1 tab
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Your main component. | |
const MyComponentWrapper = (props) => { | |
// Watch changes to local storage, and if we logout in 1 tab, | |
// logout in every other tab. | |
const syncLogout = (event: StorageEvent): void => { | |
if (event.key === 'logout') { | |
Router.push('/login'); | |
} | |
}; | |
useEffect(() => { | |
window.addEventListener('storage', syncLogout); | |
return () => { | |
window.removeEventListener('storage', syncLogout); | |
window.localStorage.removeItem('logout'); | |
}; | |
}, []); | |
return (<div>your component stuff</div>); | |
}; | |
// Somewhere else, as a handler for your `/logout` route. | |
const logout = (): void => { | |
// 1. Hit your own backend /logout API so you can invalidate the current token. | |
// 2. Delete current user's token. | |
// 3. Now set the 'logout' key in local storage that will be picked up by the storage event listener. | |
window.localStorage.setItem('logout', Date.now().toString()); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@paambaati
I have one question for this source.
Which should be
// Your main component.
?Sorry I just wondering, I'm from Vue.
For example:
If we have an App.vue is the very top component, and it's a wrapper.
So which should be the "
// Your main component.
"Thank you for your very useful script.