【发布时间】:2022-01-11 11:04:47
【问题描述】:
我有一个使用 Firebase onSnapshot 监听器的 Vue 组合。
当该侦听器上的数据发生更改时,我希望它更新名为 documentsArray 的 ref。
当我 console.log documentsArray inside onSnapshot 函数时,它似乎正在工作,因为它包含一个值数组。但是当我 console.log outside onSnapshot 函数时,数组是空的。
为什么会这样?
onSnapshot 函数外部的 console.log 也应该包含值数组。
这是我的可组合(我正在使用 TypeScript):
import { ref, Ref, watchEffect } from "vue";
import { projectFirestore } from "@/firebase/config";
import {
collection,
query,
orderBy,
onSnapshot,
DocumentData,
Timestamp,
} from "firebase/firestore";
interface Document {
id: string;
message: string;
name: string;
createdAt: Timestamp;
}
const getCollection = (
collectionString: string
): {
documentsArray: Ref<Document[] | null>;
error: Ref<string | null>;
} => {
const documentsArray = ref<Document[] | null>(null);
const error = ref<string | null>(null);
const colRef = collection(projectFirestore, collectionString);
const colRefOrdered = query(colRef, orderBy("createdAt"));
const unsubscribe = onSnapshot(
colRefOrdered,
(snap) => {
const results: Document[] = [];
snap.docs.forEach((doc: DocumentData) => {
doc.data().createdAt && //Ensures the server timestamp has been added
results.push({
...doc.data(),
id: doc.id,
});
});
documentsArray.value = results;
console.log("documentsArray.value inside snapshot", documentsArray.value); //<-- This works. It prints an array of documents.
error.value = null;
},
(err) => {
console.log(err.message);
documentsArray.value = null;
error.value = "could not fetch data";
}
);
watchEffect((onInvalidate) => {
onInvalidate(() => {
unsubscribe();
});
});
console.log("documentsArray.value outside snapshot", documentsArray.value); //<-- This does not work. It prints an empty array.
return { documentsArray, error };
};
export default getCollection;
【问题讨论】:
标签: typescript firebase vue.js google-cloud-firestore vue-composition-api