我正在使用Vue 3创建一个Firebase composable,订阅
onSnapshot()
流动
我试图通过调用返回的
unsubscribe()
内部功能
watchEffect
和
onInvalidate
。
Here are the Vue docs that explain those particular functions
。
使用
console.log()
我可以确认
watchEffect
正在开火。
但我不能触发第二个
安慰日志()
存在于内部的
onInvalidate公司
,因此我不确定
取消订阅()
函数始终被调用。
在下面的代码中,为什么
console.log("unsubscribe fired");
曾经开火吗?
除此之外,我如何才能确保我已从Firestore流中取消订阅?Firebase仪表板或类似的仪表板中是否有此日志?
以下是Vue Firestore可组合(它是用TypeScript编写的):
import { ref, reactive, watchEffect } from "vue";
import { projectFirestore } from "@/firebase/config";
import {
query,
orderBy,
onSnapshot,
DocumentData,
collection,
} from "firebase/firestore";
const useCollection: any = (col: any) => {
const documents = reactive<Record<string, unknown>[]>([]);
const error = ref<string | null>(null);
// references
const collectionReference = collection(projectFirestore, col);
const collectionOrdered = query(
collectionReference,
orderBy("createdAt", "desc")
);
// updates
const unsubscribe = onSnapshot(
collectionOrdered,
(snapshot) => {
snapshot.docs.forEach((doc: DocumentData) => {
documents.push({ ...doc.data(), id: doc.id });
});
error.value = null;
console.log(documents);
},
(err) => {
console.log(err.message);
documents.splice(0);
error.value = err.message;
}
);
watchEffect((onInvalidate) => {
console.log("watchEffect fired"); //This fires
onInvalidate(() => {
unsubscribe();
console.log("unsubscribe fired"); //This does not fire
});
});
return { documents, error };
};
export default useCollection;