Vibha
Vibha

Reputation: 13

How to do server call on browser close/tab close in react

In React Application trying to do server call to save data using redux saga in react js on browser close/tab close using JavaScript events, but it closes the browser before calling service.

onClose = () =>{
  return this.props.saveData()  // saveData will save data using redux saga.
}

componentDidMount() {
  window.addEventListener('beforeunload',this.close);
}

componentWillMount() {
  window.addEventListener('beforeunload',this.onClose);
}

It is expected to call service and save data before closing browser or tab but it closes browser before calling service to save data

Upvotes: 1

Views: 6088

Answers (2)

Alwin Jose
Alwin Jose

Reputation: 773

Browser close will not wait untill your service reach server and returns. Better you can change your implementation based on the below stackoverflow answer.

Trying to detect browser close event

Update:

Please try to return a boolean from your api and from that you can understood the hit reached to server. Then you can returning the close event to browser.

onClose = () =>{
   let status = this.props.saveData();  // saveData will save data using redux saga.
   if(status){
      return;
}

Updated:

onClose = () =>{
   let status = this.props.saveData();  // saveData will save data using redux saga.
   if(status){
      return;
}

componentDidMount() {
  setTimeout(function() {
     window.addEventListener('beforeunload',this.close);
  }, 2000);
}

componentWillMount() {
}

Upvotes: 0

hugo
hugo

Reputation: 3231

One solution would be to establish a websocket connection on page load.

Closing the tab/browser will close the connection, and your server will know immediately.

A well-established solution is socket.io, offering fallback to “long-polling” or regular polling if websockets aren’t available (you would need an “event based” approach to handling requests in that case).


According to jfriend00's answer to Websockets and scalability, they are pretty scalable:

A single server, configured appropriately can handle hundreds of thousands of simultaneous webSocket connections that are mostly idle since an idle webSocket uses pretty much no server CPU.

Upvotes: 1

Related Questions