Click here to Skip to main content
14,486,686 members
Rate this:
Please Sign up or sign in to vote.
Hi, I am working on a react project. My requirement is to clear redux store when ever the use closes the browser. (Not on Refreshing the page.)

i have done some research on it and found about EventListner events "beforeunload".
Here what i have tried.

_props.ActionSessionClear() : clears my redux state.
Every things works fine but it clears my redux state when ever i refresh the page.
And another issue is when i try to close the tab(chrome), it prompts me leave page? and even if i click on cancel, it clears my Redux State.
In IE it behaves Differently.

My requirement is just to clear the redux state. i dont need any message before closing the tab or refreshing the tab. I dont wann clear state on page refresh.


Is there any other approach to do the same??
A quick suggestion would be appreciated. Thank you!!!

What I have tried:

componentDidMount() {
    window.addEventListener("beforeunload", this.callEvent);
 }


componentWillUnmount() {
      window.removeEventListener("beforeunload", this.callEvent);
    }

callEvent = e => {
    const _props = this.props;
    e.preventDefault();
    _props.ActionSessionClear();
    localStorage.removeItem("HASTOKEN");
    _props.ActionRouteNavigate(ROUTES.LOGIN);
    var confirmationMessage = "o/";
    (e || window.event).returnValue = confirmationMessage; //Gecko + IE
    return confirmationMessage; //Webkit, Safari, Chrome
  };
Posted
Updated 5 days ago
Comments
ZurdoDev 24-Mar-20 12:53pm
   
No, I have never seen a solution that works in all cases. The beforeunload is the only option that I am familiar with.

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

If you return a value from the beforeunload event, the browser will display a confirmation message to the user asking whether they want to leave the page.

By the time the user clicks "cancel", your code has already run, and your state has been cleared.

You could use the unload event instead, which will fire just before the page is unloaded. However, there is no way to know why that unload is happening - the user could be closing the tab, navigating to a different site, navigating to a different page in the same site, or reloading the page.

If you just want storage which will be cleared when the user closes the tab, you could use sessionStorage instead of localStorage.

Window: beforeunload event - Web APIs | MDN[^]
Window: unload event - Web APIs | MDN[^]
Window.sessionStorage - Web APIs | MDN[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100