Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Cloud Firestore onSnapshot() only trigger on changes, and not get the initial state?

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?

like image 636
Thomas David Kehoe Avatar asked Oct 23 '18 18:10

Thomas David Kehoe


People also ask

What is firestore onSnapshot?

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.

What does firebase firestore () do?

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.

How do I unsubscribe from onSnapshot?

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.


2 Answers

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.

like image 165
Doug Stevenson Avatar answered Sep 20 '22 06:09

Doug Stevenson


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}`);
});
like image 35
TheNeatz Avatar answered Sep 19 '22 06:09

TheNeatz