Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore unsubscribe to updates

I am following this Google Cloud Firestore example on YouTube and getting real time updates successfully. However, I don't know how to unsubscribe to updates because it's not explained in the video. I read the documentation to create an unsubscribe() function but it doesn't work for me.

	getRealtimeUpdates = function(document) {
		firestore.collection("collection_name")
			.onSnapshot(function(querySnapshot) {
			querySnapshot.forEach(function(doc) {
				if (doc && doc.exists) {
					const myData = doc.data();
					// DO SOMETHING
				}
			});
		});
	}
like image 846
topace Avatar asked Nov 05 '18 16:11

topace


People also ask

How do I unsubscribe from firestore listener?

To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].

How do I unsubscribe from snapshot?

onSnapshot() function returns a unsubscribe function. Just call it and you should be guchi. Returns An unsubscribe function that can be called to cancel the snapshot listener.

What is unsubscribe in firebase?

A function returned by onSnapshot() that removes the listener when invoked.

What is onSnapshot in firebase?

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.


1 Answers

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

You can also find another example here: How to remove listener for DocumentSnapshot events (Google Cloud FireStore)

Here is a snippet I created that should work:

let unsubscribe;

getRealtimeUpdates = function(document) {
		unsubscribe = firestore.collection("collection_name")
			.onSnapshot(function(querySnapshot) {
			querySnapshot.forEach(function(doc) {
				if (doc && doc.exists) {
					const myData = doc.data();
					// DO SOMETHING
				}
			});
		});
	}
  
  // unsubscribe:
  
  unsubscribe();

Path to the corresponding Firebase Documentation:

https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference#onSnapshot

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

like image 200
GeraltDieSocke Avatar answered Sep 20 '22 03:09

GeraltDieSocke