window.addEventListener('storage', e => {
if(e.key === 'access_token' && e.oldValue && !e.newValue) {
store.dispatch(userSignOut());
}
})
If this is a suitable solution, then where(lifecycle event) should i paste this?
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.
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.
The best way to do that is by using the BrodcastChannel
feature in Javascript. The Broadcast Channel API allows simple communication between browsing contexts (that is windows, tabs, frames, or iframes) with the same origin (usually pages from the same site).
For example:
// Connecting to a broadcast channel
const userChannel = new BroadcastChannel('user');
function signOut() {
// and after that, we have to broadcast a message to the user channel which user has signed out from the application as below:
userChannel.postMessage({
userId: "", // If the user opened your app in multi-tabs and signed-in with multi accounts, you need to put the userId here to identify which account has signed out exactly
payload: {
type: "SIGN_OUT"
}
});
}
}
So we created the user's BrodcastChannel but we need to observe on sent messages by user's channel and do the right actions by payload type.
userChannel.onmessage = data => {
if(data.payload.type === "SIGN_OUT") {
// As I talked before about multi-accounts, we need to check the current user id with the sent userId by the userChannel and if they were the same, we have to dispatch the userSignOut action.
store.dispatch(userSignOut());
}
}
enter link description here
Try with focus Listener isFocused
Also check
React Navigation emits events to screen components that subscribe to them:
willFocus - the screen will focus
didFocus - the screen focused (if there was a transition, the transition
completed)
willBlur - the screen will be unfocused
didBlur - the screen unfocused (if there was a transition, the transition
completed)
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