Reputation: 328
I'm trying to get the sync status for a document with multiple child collections in Firestore.
The app supports both online and offline. Before the user closes a screen I want to check whether all data in the document has synced to the cloud.
What I have tried currently is the hasPendingWrites
attribute. But I always get false
.
db.collection("cities").doc(city.id).onSnapshot((querySnapshot)=> {
console.log(querySnapshot.metadata.hasPendingWrites);
});
Edit - I'm updating documents in nested collections of the city. Can it be the issue?
My collection structure
cities document (which I'm listening to the sync status)
├─── leaders collection (which I'm updating)
├─── fleet collection (which I'm updating)
├─── roads collection (which I'm updating)
├─── maps collection (which I'm updating)
Upvotes: 2
Views: 239
Reputation: 1633
collectionGroup is a special function to permit you to access collections from their names irrespective of where they are.
The advantage is it permits you to access subcollections across various documents. So you can have collectionGroup('leaders')
instead of collection('leaders') and it is to it that you will attach the snapshot listener of hasPendingWrites. And you would have to do the same for the other subcollections like 'fleet', 'roads', and 'maps'.
Note that this might unnecessarily increase read/write costs for documents in Firebase when your produce scales.
Have parts of the UI that let the user know the importance of their internet connection. Maybe preventing access entirely, showing some vector or banner if the user is not having good internet.
This solution is better because detecting sync status on your own would be an overkill. It's not just a Firebase thing. Even if you were implementing custom WebSockets by yourself. Besides Firebase has auto-syncing properties already, which is the .onSnapshot()
method itself.
Also, you can't tell if the user is trying to uninstall a mobile app when they are not connected to the internet? Sync can't take place and data will be lost. So it is best to make them feel that the product is more of online stuff. Besides, almost everything is online today.
Upvotes: 1