0

I would like to detect a refresh page (f5 or the refresh button in the browser) in react in order to perform function. Basically i would like to call an API when the refresh is pushed and to call this API, i need some state value. Does someone has an idea how to do that? Thanks

EDIT:

 useEffect(() => {
    console.log("use effect called");
    window.addEventListener('beforeunload', handleEndConcert);
     return () => {
      // hit endpoint to end show
      window.removeEventListener('beforeunload', handleEndConcert);
      //handleEndConcert();
    }
  }, []);

  const handleEndConcert = () => {
    console.log('Stop this');
    console.log(selectedFile);
  }
Jimjim
  • 141
  • 1
  • 4
  • 10
  • I think you are looking this https://stackoverflow.com/a/18704284/12656448. User will see your massage in prompt. – Kirill Skomarovskiy Dec 03 '20 at 03:55
  • thanks. is there a way to also trigger a function if the user decide to close the page ? – Jimjim Dec 03 '20 at 03:58
  • Does this help you: https://stackoverflow.com/questions/64966559/is-there-a-function-like-componentwillunmount-that-will-fire-before-the-page-i/64967211#64967211 – Drew Reese Dec 03 '20 at 05:25

1 Answers1

0

Based on your code, which I realized is similar to my linked answer I reread what you are actually asking for.

If I understand your question/issue, you are trying to invoke a function when the component unmounts but has access to the latest state. You can use a react ref and a second effect hook to capture state updates.

const [selectedFile, setSelectedFile] = React.useState(....);

const selectedFileRef = React.useRef(selectedFile); // ref to store state value

React.useEffect(() => {
  selectedFileRef.current = selectedFile; // save selectedFile state value to ref
}, [selectedFile]);

...

useEffect(() => {
  const handleEndConcert = () => {
    console.log('Stop this');
    console.log(selectedFileRef.current); // <-- access current ref value
  }

  console.log("use effect called");

  window.addEventListener('beforeunload', handleEndConcert);

  return () => {
    // hit endpoint to end show
    window.removeEventListener('beforeunload', handleEndConcert);
  }
}, []);
Drew Reese
  • 165,259
  • 14
  • 153
  • 181