React JS: Is beforeunload fired on page refresh?

Viewed 875

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.

1 Answers

Thanks to comments, found a workaround with cookies. When the user logs in, add a cookie,

this.setState({currentUser:JSON.parse(localStorage.getItem("currentUser"))});
document.cookie = "userLoggedIn=true";

And modified componentDidMount() as follows,

componentDidMount() {
    var c = this.getCookie("userLoggedIn");

    if(localStorage.getItem("currentUser") !== null && c == "true")
    {
      let currentUser = localStorage.getItem("currentUser");
      this.setState({currentUser:JSON.parse(currentUser)});
    }
}

getCookie() from https://www.w3schools.com/js/js_cookies.asp

If the window was closed, cookie won't be there. No need for any events like 'beforeunload'

Related