0

I'm currently using a Firestore backend. What I want to achieve is to update a document on Firestore when the window closes. I know we could use Navigator.sendBeacon() to call an API when a window closes because it receives url and data (optional) as its parameters. However, I want to instead execute a function, for example from Firestore, there is a function called updateDoc. Is there a way I could achieve this?

Or is there any other approach I could use?

Owenn
  • 638
  • 1
  • 6
  • 23

1 Answers1

0

According to this Documentation :

There is a function firebase.database.onDisconnect. The onDisconnect class allows you to write or clear data when your client disconnects from the Database server. These updates occur whether your client disconnects cleanly or not, so you can rely on them to clean up data even if a connection is dropped or a client crashes.

method update:

update ( values : Object , onComplete ? : ( a : Error | null ) => any ) : Promise < any >

Writes multiple values at this location when the client is disconnected (due to closing the browser, navigating to a new page, or network issues).

The values argument contains multiple property-value pairs that will be written to the Database together. Each child property can either be a simple property (for example, "name") or a relative path (for example, "name/first") from the current location to the data to update.

As opposed to the set() method, update() can be use to selectively update only the referenced properties at the current location (instead of replacing all the child properties at the current location).

See more examples using the connected version of update().

var ref = firebase.database().ref("users/ada");
ref.update({
   onlineState: true,
   status: "I'm online."
});
ref.onDisconnect().update({
  onlineState: false,
  status: "I'm offline."
});
Sathi Aiswarya
  • 2,068
  • 2
  • 11
  • This seems to be the answer I'm looking for! However, I'm currently using web modular v9 where I use `updateDoc()` instead of `.update()`. How can I implement `onDisconnect` with `updateDoc()`? I can't seem to find it in the documentation. – Owenn Oct 09 '22 at 06:13
  • @Owenn I can see you have asked this question at [link](https://stackoverflow.com/questions/74002533/how-to-use-ondisconnect-in-firebase-v9-reactjs) and there is already answer provided for your post. – Sathi Aiswarya Oct 10 '22 at 12:35