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');
}
}
)
The firestore. collection(). onSnapshot() function returns a unsubscribe function. Just call it and you should be guchi.
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.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With