React call function before window/tab close

Viewed 8451

I am trying to call a function when user closes the tab on window. As per my research, i found the following way to achieve the same using window's beforeunlaod event :

componentDidMount(){
  window.addEventListener('beforeunload', (ev) => {
    this.props.apiCall(); // calling an api to update some data
 })
}

It seems that the above code is not working properly as the respective function(apiCall()) is not getting called.

Can someone please help me to resolve the same.

1 Answers

As per docs, your EventListener should be like this,

window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';

  this.props.apiCall();
});
Related