I need to let the server know when the user closes or reloads the page. I'm listening to the "beforeunload" event and when the function is called I'm sending an axios call to the server. It works when refreshing the page but not when closing it and I don't know how to fix it.
Here is my code
componentDidMount() {
window.addEventListener("beforeunload", this.endSession);
}
componentWillUnmount() {
window.removeEventListener("beforeunload", this.endSession);
}
endSession = (e) => {
axios
.post(Globals.backendServer + "/session/end", {
sessionData: this.state.sessionData,
})
.then((res) => {})
.catch((err) => {
alert(err);
});
};
There is no guarantee that asynchronous actions executed in the beforeunload
event will complete, and axios uses an asynchronous way of making requests.
You can probably use good old XHR to make a synchronous request. If you go to the section labeled Adapting Sync XHR use cases to the Beacon API
, they will go over strategies of keeping requests alive during unload because synchronous XHR is deprecated.
Note that synchronous HTTP requests are generally a bad idea because they will render the page unresponsive while they are completing. I'm not sure what the behavior would be for a synchronous request during unload.