0

The confirm alert shows before the users are going to move from the page in React. If they respond YES, I want to run onDelete(). The below code runs onDelete() if they respond NO also.

componentDidMount() {
  this.setupBeforeUnloadListener();
}

setupBeforeUnloadListener() {
  window.addEventListener("beforeunload", (event) => {
    event.returnValue = `Are you sure you want to leave?`;
    this.onDelete();
  })
}

How can I run onDelete() only if the users respond YES in confirm alert.

k10a
  • 947
  • 2
  • 11
  • 30

1 Answers1

1

You can try using the unload event together with beforeunload. beforeunload will give the user the chance to cancel the unload, and the unload event will be triggered if the user does not cancel the unload.

Note that most browsers ignore any custom prompt string https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Browser_compatibility

When this event returns (or sets the returnValue property to) a value other than null or undefined, the user will be prompted to confirm the page unload. In older browsers, the return value of the event is displayed in this dialog. Starting with Firefox 44, Chrome 51, Opera 38, and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example:

Firefox displays the string, "This page is asking you to confirm that you want to leave - data you have entered may not be saved." (see bug 588292). Chrome displays the string, "Do you want to leave this site? Changes you made may not be saved." (see Chrome Platform Status).

Also, if your onDelete() function does anything asynchronous it's not guaranteed to complete. See this discussion for more info: What are the limitation using before unload event?

Casey Flynn
  • 13,654
  • 23
  • 103
  • 194