Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop onSnapshot function in firestore

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'); 
    }
  }
)
like image 335
labo28 Avatar asked Dec 26 '18 23:12

labo28


People also ask

How do I turn off onSnapshot firestore?

The firestore. collection(). onSnapshot() function returns a unsubscribe function. Just call it and you should be guchi.

What is firestore onSnapshot?

You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.

Is cloud firestore real time?

Firebase offers two cloud-based, client-accessible database solutions that support realtime data syncing: Cloud Firestore is Firebase's newest database for mobile app development. It builds on the successes of the Realtime Database with a new, more intuitive data model.


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();
    }
  }
like image 92
Doug Stevenson Avatar answered Sep 30 '22 20:09

Doug Stevenson