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?
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?
Share Improve this question asked Jul 13, 2017 at 0:48 Geno DiazGeno Diaz 5101 gold badge8 silver badges21 bronze badges 3- Does this question help: stackoverflow./questions/26059762/… – Andre M Commented Jul 13, 2017 at 0:51
- @AndreM I am looking to call an API before leaving the page not on entering. – Geno Diaz Commented Jul 13, 2017 at 0:53
-
Similar approach, but listen for the
beforeunload
event.ponentWillUnmount()
might do the trick as well, though I haven't tried or pared the scenarios within React. – Andre M Commented Jul 13, 2017 at 1:00
1 Answer
Reset to default 5You can use thew window.unload event (https://developer.mozilla/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 ponentWillUnmount could not resolve properly your problem, because react could call that event though the browser is not refresh or close.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744187391a4562271.html
评论列表(0条)