Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hook cleanup when refreshing the page

I have an app built in React using hooks that when closed needs to notify the server. I tried doing it using the following approach:

function onUnload() {

        if (roomID !== "")
            endGame(roomID, dispatch);
    }

    useEffect(() => {
        return onUnload;
    },[])

Here, endGame is a function that performs a HTTP request to the backend. But when refreshing the page to emulate a user closing the app, the request never reaches the server, meaning that the cleanup function doesn't get executed. Any ideas on what is wrong?

Thanks in advance

like image 796
Adrian Pascu Avatar asked Jul 31 '26 08:07

Adrian Pascu


1 Answers

Refreshing the page is not same as component unmount. When you refresh the page, the React state is reset as React solely works on the current client session and refresh is equivalent to resetting it. What you are lloking for might be the onunload event. Try this:

window.onbeforeunload = function(e) {
  return onUnload();
};
like image 164
Easwar Avatar answered Aug 03 '26 07:08

Easwar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!