Stop onSnapshot function in firestore

Viewed 4026

Does anyone have any idea how to get out the onSnapshot function in firestore. I want to if the if condition fulfilled that the function will leave and the database request will exit. The function is called by onClick and the first step ist to add something in the database. The second step should be that if it already something in the collection then stop the realtime request and stop the function after you add your information in the database. The user should not notice anything more of the function that means no more updates from the database. I hope someone can help me.

  db.collection('Requests').doc('lobby1').collection('1').add({
            name: 'test',
            createdAt: Date.now()
        }).catch(err =>{
            console.log(err)
        })  

  let ref= db.collection('Requests').doc('lobby1').collection('1')
  ref.onSnapshot(snapshot => {
    console.log(snapshot.size)
    if(snapshot.size >= 2){
        console.log('Test'); 
    }
  }
)
1 Answers

According to the API documentation, onSnapshot() returns

An unsubscribe function that can be called to cancel the snapshot listener.

and shows an example of its usage.

  const unsubscribe = ref.onSnapshot(snapshot => {
    console.log(snapshot.size)
    if(snapshot.size >= 2){
        console.log('Test'); 
        unsubscribe();
    }
  }
Related