Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How multi-tab logout can be managed in reactJS?

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?

like image 309
Aditya V Avatar asked Nov 12 '19 07:11

Aditya V


People also ask

How do I logout of multiple tabs in react?

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.

How user will logout from all open tabs automatically when user logs out in one of them?

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.


2 Answers

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());
   }
}
like image 58
Ali Torki Avatar answered Sep 27 '22 21:09

Ali Torki


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)
like image 44
Manoj Perumarath Avatar answered Sep 27 '22 21:09

Manoj Perumarath