Cytronic
Cytronic

Reputation: 213

How to skip initial data from onSnapshot listener in Firestore Firebase?

I want to use a notifications collection as a sort WebSocket connection for one-time toast notifications, say for when a user deposits cryptocurrency and it has been confirmed. The logic behind it would be that a cloud function listens for documents being added to a collection.

I tried listening to real-time updates from the said collection and limiting it to the last one created, but the problem that I am having now is that I don't want the user to immediately get their last toast notification when they reload... i.e if the user isn't active I don't want the user to see the notification the next time they do become active.

I want them to be exactly what they are, one-time toast notifications only for then the user is active. So my question is, is there any way to skip that initial data from the onSnapshot listener?

Upvotes: 2

Views: 1644

Answers (2)

fakeplasticandroid
fakeplasticandroid

Reputation: 143

You can declare a stateful function that can repeatedly by invoked with a callback, but always skips the first time.

function skipFirst(operation) {
  let firstTime = true;
  return function () {
    if (firstTime) {
      firstTime = false;
    } else {
      operation();
    }
  };
};

Let say you have a snapshot handler like:

function onSnapshot(data) {
   // do something with the data
}

You can then wrap your handler function and pass it into the onSnapshot listener like so: skipFirst(onSnapshot)

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

Firestore listeners return the data that you request, and then listen for updates to that data. There is no way to skip the initial data and only receive the updates, but you can typically change what data you request.

For example, if you ensure each document in your collection has a timestamp of when it was created, you can use a query to only request data that was created after you start listening with:

collectionRef.where("timestamp", ">=", firebase.firestore.Timestamp.fromMillis(Date.now()));

Upvotes: 7

Related Questions