Reputation: 421
I saw on the Firestore documentation for realtime listener that we can view changes between snapshots and see whether each document is added, removed or modified.
I am wondering if it is possible to see the type of changes if I am only attaching onSnapshot
to a single document?
I tried to run the docChanges()
method on the single doc listener:
db.collection("matching").doc("user1").onSnapshot(async doc => {
doc.docChanges().forEach(function(change) {
if (change.type === "added") {
console.log("added: " + change.doc.data());
}
})
})
But it produced an error of :
Uncaught (in promise) TypeError: doc.docChanges is not a function
I think I simply cannot run docChanges()
on a single doc listener. In that case, how to view changes for a single firestore doc realtime listener then?
Upvotes: 1
Views: 1349
Reputation: 79
While it's established that you cannot check for change type when you setup your listener using doc()
, you can use classic query with onSnapshot()
to use the necessary listener functionality.
const q = query(
collection(db, <your_collection_name>),
where(documentId(), '==', <your_document_id>)
)
onSnapshot(q, (snapshot) => {...your listener code here})
Upvotes: 0
Reputation: 1
This docChanges()
method is applicable on listeners being run on the collection rather than documents, so if you want to check changes between the snapshot put the docChanges()
after the collection reference.
Upvotes: 0
Reputation: 317760
No, the API will not indicate to you what data or fields changes between snapshots. You just get a callback every time something changed anywhere in the document. You have to compare the previous and current snapshot to figure that out for yourself.
Upvotes: 3