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

Viewed 8309

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?

5 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.

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}`);
});

No. Whenever you use onSnapshot, an initial call is made to get the data immediately and after that changes are listened.

But you can handle the logic within it to detect wether it was an initial call or updates trigger using the following properties provided by the firebase.

  db
  .collection("pets")
    .doc(petId)
    .onSnapshot(
      snapshot => {
        let data = snapshot.data()
          // either edit, update or delete
          if (snapshot.metadata.hasPendingWrites) { 
            if (snapshot.exists) {
              // edit or create logic
            }
            else{
             // delete logic
            }
        }
      
      },
      err => {
        console.log(err)
      }
    )

Firestore listeners loads by their own order and the "onSnapshot" event must always execute first on initial state. But, you can handle that behavior adding a initial state variable like:

var initState = true;
db.collection('col').doc('id').onSnapshot(....

Then you could validate inside the function the code you dont want to run when your application starts.

var initState = true;
db.collection('col').doc('id').onSnapshot(....
if(!initState){ // if is not initial state
   //your code
}

and after the application starts up you must change initState to false and add a sleep/timeout function (cause it may have an unexpcted asyncronous load)

var initState = true;
db.collection('col').doc('id').onSnapshot(....
if(!initState){ // if is not initial state
   //your code
}

setTimeout(function () { // cause onSnapShot executes first
   initState = false;
}, 2000);

What also worked for me was to check for the document.readystate and then choose to act on the snapshot changes. Like this -

db.collection("collectionName").onSnapshot( (snapshot) => {
    console.log(snapshot.docChanges())
    if( ["loaded","interactive", "complete"].indexOf(document.readyState) >=0 ){
        <-----Your code to act on the snapshot changes---->

}

Based on the readystate property documentation here - https://www.w3schools.com/jsref/prop_doc_readystate.asp

Related