I have following code in my App.js. What I want to do is log out the user when the window is closed.
componentDidMount() {
if(localStorage.getItem("currentUser") !== null)
{
let currentUser = localStorage.getItem("currentUser");
this.setState({currentUser:JSON.parse(currentUser)});
}
window.addEventListener("beforeunload", this.unload);
}
unload = (e) => {
console.log('unload...')
localStorage.clear();
}
localStorage is cleared and user is logged out when the windows is closed, but the same seems to happen when the page is refreshed (although the console.log is not executed). Can I stop firing unload() method on page refresh? Is there a better way to logout (clear localStorage) when the browser window is closed? sessionStorage is not an option as it is cleared on tab close. Thanks.
Edit: As Mohit pointed out I tried adding event listener inside componentWillUnmount(), and the user was not logged out on window close.