Get real time updates on Firestore documents which have been changed within the last 10 minutes

Viewed 23

I can get updates on documents which have been changed after a given timestamp like this:

const q = query(collection(db, "items"), where("lastChange", ">", "1654249598"));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
  // ...
});

However, I want to get updates only on documents, which have been changed in the past 10 minutes, and I want to keep listening indefinitely. So if the lastChange property starts to be lesser than 10 minutes ago, it would be removed from the documents snapshot with change == 'removed'

So I would want to use something like:

const tenMinutes = 10*60
const constraint = where("lastChange", ">", firestore.FieldValue.serverTimestamp() - tenMinutes) // dynamic time filter
const q = query(collection(db, "items"), constraint);
const unsubscribe = onSnapshot(q, (querySnapshot) => {
  // ...
});

In SQL, I would write

SELECT * FROM items WHERE lastChange > now() - interval '10 minutes'

Is it possible to create such "dynamic filter" in Firestore?

1 Answers

The values in a query are immutable, while "the past 10 minutes" changes over time. Thus means there is no way to create the behavior you want in a single Firestore query.

You can either disqualify results outside of the required range in your client-side code, recreate the query regularly to match the current time, or a combination of the two.

Related