H.O.K
H.O.K

Reputation: 29

how to unsubscribe nested real time firebase cloud firestore database?

I'm new to web development. I'm trying to unsubscribe real time listener from firestore with nested listening for relations. I tried let unsub = db.collection().onSnapshot(()=>{}); unsub(); from firestore document , but it doesn't work.

It's a nested listener something like :

 db.collection('apple_orange').where('orange_id','==',orangeID).onSnapshot((querySnapshot=>{
    querySnapshot.docChanges().forEach(change => {
      if(change.type ==='added'){
          db.collection('apple_mango').where('apple_id','==',change.doc.data().appleID).onSnapshot((querySnapshot=>{
            querySnapshot.docChanges().forEach(change=>{
              if(change.type === 'added'){
                  // do something
              }
            })
          }))
      }
      if(change.type ==='removed'){
        //unsubscribe listener of apple_mango query
        let unsub = db.collection('apple_mango').where('apple_id','==',change.doc.data().appleID).onSnapshot(()=>{})
        unsub()
      }

    });
  }))

Is it even possible to do this ? Please help.

Upvotes: 0

Views: 214

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

Don't create a new Query to unsubscribe. Use the unsubscribe function from the original Query.

const unsub = db.collection(...).where(...).onSnapshot(querySnapshot => {
    if (time_to_unsub) {
        unsub()
    }
})

You might have to change the scope of unsub to match what you're trying to do. But either way, don't create a new Query just to unsubscribe.

Upvotes: 2

Related Questions