0

I'm using Firebase for my chat application, and I'm using a snapshot listener on my list collection to get only the records that have been updated recently. Because snapshot returns all of the collection records  in the results of snapshot listener, I want to limit the results here in the snapshot to reduce my Firebase usage limit, especially if my doc changes in the collection.

Thus we maintain a property in every document called updatedOn. Which will tell us the document updated time in milliseconds. where updatedOn = Date.now() (time in milliseconds)

    var db = this.getFirestore();
      db.collection("collection1")
      .doc("doc1")
      .collection("list")
      .where('updatedOn', '>=', MAX_UPDATED_TIME_VISITOR)
      .onSnapshot((datas) => {
            datas.forEach((data) => {
                mainData = data.data()
                if (MAX_UPDATED_TIME_VISITOR < mainData.updatedOn){
                    MAX_UPDATED_TIME_VISITOR = mainData.updatedOn; 
                    // second time i want to use this updated value of MAX_UPDATED_TIME_VISITOR
                   //  in where condition of snapthot
                }
            })
      });        
};

On the client-side. While query the data, we’ll add a where condition to only query documents which have updatedOn value greater than MAX_UPDATED_TIME_VISITOR value.

Where MAX_UPDATED_TIME_VISITOR is max of all the updatedon values present in my collection its value changes when we get the result. and I want to send this modified value of MAX_UPDATED_TIME_VISITOR in snapshot how can I do this ?

I have checked on Google and StackOverflow that we get all the documents from the cache in snapshot listener which are not modified and I have checked by using this

data.metadata.fromCache and it is returning false always. So here I only want to fetch the modified data or limit the resultsets of my Firebase snapshot listener.

Gourav B
  • 864
  • 5
  • 17

1 Answers1

1

onSnapshot fetches the initial source from cache and subsequently from the server as mentioned in the Stackoverflow case. "fromCache" flips from true to false once the backend has sent us all documents that matched the query when the query was issued. It indicates that the server has caught up with our request. Afterwards, the server will send us updates in real-time and we don't flip back to "fromCache: true" (unless the network connection is lost).

Referring to the Stackoverflow case states that, fromCache may not contain all data from the server yet.

Contrarily, the hasPendingWrites method may contain data that the server doesn't know about yet. That is, retrieved documents that have a metadata.hasPendingWrites property indicates whether the document has local changes that haven't been written to the backend yet. You may refer to this document for more details on the hasPendingWrites method.

Mousumi Roy
  • 609
  • 1
  • 6