Firestore unsubscribe to updates

社会主义新天地 提交于 2020-08-24 07:41:42

问题


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
				}
			});
		});
	}

回答1:


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.



来源:https://stackoverflow.com/questions/53157997/firestore-unsubscribe-to-updates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!