rID133
rID133

Reputation: 163

Nested Firestore listeners and how to unsubscribe from created listeners

I want to use a nested listener structure like this one:

snapshotListeners() {
  firestore()
    .collectionGroup()
    .where()
    .onSnapshot({
      error: //Handle error
      next: firstSnapshot => {
        firstSnapshot.docsChanges().forEach(change => {
          //Data retrieved and used in the below query to get more data
          firestore()
            .collection()
            .where() //using the data retrived from the above query here.
            .onSnapshot({
              error: //Handle error
              next: secondSnapshot => {
                secondSnapshot.docsChanges().forEach(change =>{
                  //More Data from second query
                })
              }
            })
        })
      }
    })
}

which is a borrowed snippet from Nesting firestore onSnapshot listeners in react-native?

I am unsure how best to keep track of the listeners created when the outer listener fires. How can I unsubscribe the previous inner listener when a new inner listener is created? Would overwriting an old listener's variable unsubscribe it? i.e

 var unsubscribe = old_listener 

 unsubscribe = new_listener
  // would this unsubscribe old listener?
 
 

If not, then what's a good way to keep track of them? Frank hints at using a list which makes sense but I'm a Javascript beginner and not sure how to implement it. I can append each new listener to a list but how would I then call them as a function to unsubscribe?

Upvotes: 1

Views: 1064

Answers (2)

rID133
rID133

Reputation: 163

I solved this by first declaring var unsub as a dummy function. I used unsub = () => {} which returns undefined. I then declare my outer listener which when triggered will call unsub before assigning unsub to my new inner listener, i.e. unsub = firestore().collection(..).OnSnapshot().... This ensures that each time the outer listener triggers, the previous inner listener is detached before attaching a new listener.

Upvotes: 2

Kevin Moe Myint Myat
Kevin Moe Myint Myat

Reputation: 2165

firestore.collection().onSnapshot() 

will return a unsubscribe function. Declare the unsubscribe variable and assign the onSnapshot to it.

After that, you can unsubscribe by calling the function.

e.g,

const unsubscribe = firestore.collection("collection_name")
        .onSnapshot(() => { 
// call another snapshot or handle the snapshot data
});

When you are done, just unsubscribe by

unsubscribe();

You can find more examples at Firestore unsubscribe to updates

Upvotes: 1

Related Questions