Is there a function, like componentWillUnmount, that will fire before the page is refreshed
Asked Answered
S

2

0

I want a function, to send a request to a server (don't care about response) before a user refreshes the page.

I've tried using the componentWillUnmount approach but the page refresh doesn't call this function. e.g.

import React, { useEffect } from 'react';

const ComponentExample => () => {
    useEffect(() => {
        return () => {
            // componentWillUnmount in functional component.
            // Anything in here is fired on component unmount.
            // Call my server to do some work
        }
    }, []) }

Does anyone have any ideas how to do this?

Shanell answered 23/11, 2020 at 10:25 Comment(5)
componentDidMount() is the function you should be using.Zama
Check this answer for native eventLamentable
componentDidMount() will fire when the component loads. I want a function to fire when the page is about to refresh.Shanell
Thanks @Lamentable but that native event gives a confirmation dialog. I want a function, so I can do some work before the page refreshesShanell
You can do some work inside that function. The dialog is just the default behavior.Lamentable
S
3

You could try listening for the window.beforeunload event.

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.

useEffect(() => {
  const unloadCallback = (event) => { ... };

  window.addEventListener("beforeunload", unloadCallback);
  return () => window.removeEventListener("beforeunload", unloadCallback);
}, []);

Note: This will respond to anything that causes the page to unload though.

Note 2:

However note that not all browsers support this method, and some instead require the event handler to implement one of two legacy methods:

  • assigning a string to the event's returnValue property
  • returning a string from the event handler.
Seena answered 23/11, 2020 at 11:4 Comment(5)
Perfect. That's what I was looking for. For anyone looking here, I had to add a line to the call back: unloadCallBack = e => { // do work delete e['returnValue'] }Shanell
It's advisable you use beforeunload instead of unloadEridanus
@Eridanus Thanks. In my testing I didn't notice a difference between the two, but upon reading the official docs I agree.Seena
@DrewReese For the unloadCallback function, if it returned a e.returnValue = "Are you sure?", this would produce an alert with two options: "Cancel" and "Leave". If the user selects "Leave", do you know how to call some function, say someFunction(), right before the page refreshes? [This is a bit of an indirectly related question to the OP!]Delaminate
@Delaminate Not that I'm aware of currently. I think the idea is to either do the work in the unloadCallback, or ask the user what they want to do, and if they choose leave then the browser manages the resources. In other words, unloadCallback is that "some function". Browser maintainers have made it clear they don't want pages to keep users around any longer than they need to when users have indicated they want to leave. No more Columbo style "but hey, just one more thing..." nag screens.Seena
G
0

You can do this, almost, by checking if the page has been refreshed.

Source: https://developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API

Example:

if (window.performance) {
  console.info("window.performance is supported");
  console.info(performance.navigation.type);

  if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
    console.info( "This page is reloaded" );
  } else {
    console.info( "This page is not reloaded");
  }
}
Goto answered 23/11, 2020 at 11:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.