Home > Back-end >  How to Implement beforeunload event Listener in React
How to Implement beforeunload event Listener in React

Time:05-21

I have this rough code in Javascript, I want to implement this code in my react application but I am not sure how to implement them in react.

Overview of my requirement --

I want to clear a particular token from local storage unless the user closes all the tabs or exits the browser, so the next time user tries to open the application he needs to log in again, So I took a reference of this code, but I don't have any idea where to use this in React.

window.onbeforeunload = (event) => {
    localStorage.removeItem('logged-in');
}

let loggedIn = localStorage.getItem('logged-in');
let sessionLoggedIn = sessionStorage.getItem('logged-in');
if(!loggedIn) {
    if(sessionLoggedIn) {
        localStorage.setItem('logged-in', JSON.parse(sessionLoggedIn));
        //go to authenticated space
        window.location.href = '/authenticated';
    } else {
        //go to login
        window.location.href = '/login';
    }
} else {
    //go to authenticated space
    window.location.href = '/authenticated';
}

window.addEventListener('storage', (event) => {
    if (event.key == 'logout' && event.newValue) { 
        sessionStorage.removeItem('logged-in');
        localStorage.removeItem('logout');
        window.location.href = '/login';
    }
});

Can someone guide me on where to implement this code in react application do we need to use any hooks for watching for beforeunload event?

Any help would be much appreciable, thanks in advance!!

CodePudding user response:

With the limited information given I would say that you should put the following code into your index.js or similar.

    useEffect(() => {
      window.addEventListener('beforeunload', yourFunction)
     
      return () => {
      window.removeEventListener('beforeunload', yourFunction)
    };
  }, []);

CodePudding user response:

use it like this

useEffect(() => {
  window.addEventListener("beforeunload", handleUnloadEvent);

  return () => window.removeEventListener("beforeunload", handleUnloadEvent);
}, [handleUnloadEvent]);

I've added [handleUnloadEvent] to the 2nd attribute of useEffect to prevent adding and removing the event listener on every state change.

  • Related