Can you use an 'beforeunload' listener in an export default function? If so how?

Viewed 48

All examples I am seeing online are using React Components. I am a newbie to react. So any explanation will be helpful, and what I should do to achieve this.

export default function Review() {
...

useEffect(() => {
console.log("useeffect called")

window.addEventListener("beforeunload", save());

}, []);

...

return (...);

Here is a CodeSandbox.io link. Here you will find that I have 2 pages 1 home the other dashboard.

When I go to dashboard. I get the Alert. But Leaving Dashboard I do not get the Alert Message. beforeunload is not working how I expect it to.

https://codesandbox.io/s/react-router-basic-forked-8uvvi?file=/

2 Answers

An alternate way to call a function when a page/component is about to be unmounted is to add it as a return from your useEffect(). For example:

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

CodeSandbox Example

You are not passing an onbeforeunload callback, you are immediately invoking the alert.

useEffect(() => {
  console.log("useeffect called");
  // subscribe event
  window.addEventListener("beforeunload", alert("HI"));
}, []);

Create/define a callback that does one, or more, of the following:

  • Prevents the default on the event object
  • Assigns a string to the event object's returnValue property
  • Returns a string from the event handler.

window.beforeunload

Note: To combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with. Moreover, some don't display them at all.

Code suggestion

useEffect(() => {
  const handler = (e) => {
    // Cancel the event
    e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
    // Chrome requires returnValue to be set
    e.returnValue = "";

    // ... business logic to save any data, etc... before the window unloads
    save();

    return "";
  };

  // subscribe event
  window.addEventListener("beforeunload", handler);

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

Edit can-you-use-an-beforeunload-listener-in-an-export-default-function-if-so-how

Related