Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending API call before page reload or close using React

I am trying to send information to the backend regarding the state of the application at page reload/close. Is there a way to detect these two actions and call an API before proceeding?

like image 439
Geno Diaz Avatar asked Jul 13 '17 00:07

Geno Diaz


1 Answers

You can use thew window.unload event (https://developer.mozilla.org/en-US/docs/Web/Events/unload).

Put the code below in some point of you code (I suggest in the index.html or some entry point of the app):

window.addEventListener('unload', function(event) {
   //call function to save you state in API or save in localStore
   localStore.setItem('state', JSON.stringify(store.getState())
});

I think use componentWillUnmount could not resolve properly your problem, because react could call that event though the browser is not refresh or close.

like image 120
Henrique Oecksler Bertoldi Avatar answered Oct 20 '22 11:10

Henrique Oecksler Bertoldi