The documentation says:
You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.
I just want my listener to fire when the data changes. I don't want it to fire when the app loads, to get the initial state of the data. Any suggestions?
You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.
Cloud Firestore is a NoSQL document database that lets you easily store, sync, and query data for your mobile and web apps - at global scale.
onSnapshot() function returns a unsubscribe function. Just call it and you should be guchi. Returns An unsubscribe function that can be called to cancel the snapshot listener.
Firestore listeners don't work that way. You will always be delivered the document(s) relevant to the fetch or query, then updates after that for as long as the listener remains added. There is no mode to receive deltas only.
If you want to receive only certain data, you might want to figure out how to query for it, for example, by adding a timestamp field and having the client only query for documents that have changed since some prior time.
After reading the first and second solution, I have made a solution that seems to work.
First you initialize a variable to true
and inside the onSnapshot()
method you check if this variable is true
, if it is, you change it to false
, and on else you write your retrieving data algorithm. Something like this:
var initState = true;
let observer = records.onSnapshot(docSnapshot => {
console.log(`Received doc snapshot`);
if (initState) {
initState = false;
} else {
if (!docSnapshot.docChanges().empty) {
docSnapshot.docChanges().forEach(function (change) {
//Write here wahtever you want
});
}
}
}, err => {
console.log(`Encountered error: ${err}`);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With