代码之家  ›  专栏  ›  技术社区  ›  TinyTiger

如何使用Vue onInvalidate回调从Firestore流中取消订阅?

  •  0
  • TinyTiger  · 技术社区  · 4 年前

    我正在使用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;
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   BuzzWoods    4 年前

    因为在watchEffect的回调中没有任何反应对象

    推荐文章