0

I'm using firebase cloud to store data of the user. For sake of argument let say is their favorite movies out of a list. Now, upon using the free firebase tier I don't want to make writes to the fire-cloud every time the user marks a movie as their favorite.

My intension is to update the data in the cloud once the user either logs out(which I already know how to do) or closes the browser || tab.

Is it possible to dispatch an action before or while the process of closing a browser/tab is happening?

Is there an alternative approach for this behavior?

BAcevedo
  • 105
  • 3
  • 12

1 Answers1

2

Yes, you should leverage window:beforeunload event, accordingly to MDN :

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.

This is typically what I do in the CoreComponent of my apps when needed :

  @HostListener('window:beforeunload', ['$event'])
  beforeunloadHandler(event) {
    this.store.dispatch(SomeActions.fireTheAction());
  }
Thomas
  • 140
  • 1
  • 8
  • It kinds of work. It doesn't completely do what I expect. It works when I got back and forward in the same tab. Not doing anything when refresh/close tab/ close Browser. Do I have a limited time before it reaches the ngrx action? – BAcevedo Nov 03 '20 at 23:54
  • 1
    The NgRx action is dispatched super fast, but I assume you make an HTTP call to save data (it can takes some time !), that's why the action completes well but the API call doesn't. I personally use this event to fire a logout action over a WS (which is very fast because the connection is already established and the payload I'm sending is light). This is very opinionated, but in your case, I'm not sure you should only save data on browser exit, however, [this thread](https://stackoverflow.com/questions/276660/how-can-i-override-the-onbeforeunload-dialog-and-replace-it-with-my-own) may help. – Thomas Nov 05 '20 at 07:41