Search code examples
angularfirebasegoogle-cloud-firestoreangularfire

Firestore SnapshotChanges - Listening for New Document


I am working on creating a realtime scrolling pagination service using Firestore. I plan to write it by loading in limit of 10 real-time documents to an array that will display on screen. When the loadMore() function is called, use the startAfter function to load 10 more non-realtime documents, etc. I got this idea from Firebase's Youtube Channel

The Idea... The Problem

Once I load in some real-time documents, I want to listen for new documents in realtime, adding them or updating them in the array. collectionRef.snapshotChanges() emits a DocumentChangeAction[]. A single object in the array looks like this:

{
   doc: n {Df: e, E_: t, kf: n, Mf: false, Of: false, …}
   newIndex: 0
   oldIndex: -1
   type: "added"
}

It notates the last event the object experienced was added. Great but it doesn't notate when an object was not-seen-in-this-query-before.-aka,-just-added-and-newly-loaded.

The Question Does anyone know how to find brand new objects in realtime via firestore?

Sidenote: I could be approaching pagination all wrong but I believe this is a responsible way to achieve the task (that is, if it can be done this way).


Solution

  • Firestore doesn't maintain any sense of what a "new" document is. It sounds like you should store a timestamp in each document that records when it was created. You can then use this timestamp in a range filter to query for documents that are "new" by your definition.

    If your definition of "new" is any document greater than the greatest timestamp seen in from a prior query, then just use that timestamp value in your query. You can then listen to the results of that query to get any newer documents in real time.

    See also: Firestore query by date range