我有一個使用 FirebaseonSnapshot偵聽器的 Vue 組合。
當該偵聽器上的資料發生更改時,我希望它更新ref命名的documentsArray.
當我在函式documentsArray 內部使用console.log 時,onSnapshot它似乎在作業,因為它包含一個值陣列。但是當我在函式外console.log 時onSnapshot,陣列為空。
為什么會這樣?
函式外的console.logonSnapshot還應包含值陣列。
這是我的可組合(我使用的是 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;
uj5u.com熱心網友回復:
onSnapshot回呼內的代碼是異步運行的(在回呼外運行代碼之后),為了查看函式外的更改,您必須創建一個觀察者來查看更改:
import import { ref, Ref, watchEffect, watch } from "vue";
....
const unsubscribe = onSnapshot(
colRefOrdered,
(snap) => {
...
);
watch(documentsArray,(newVal,oldVal){
console.log("documentsArray.value outside snapshot", documentsArray.value);
},{deep:true})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/375812.html
標籤:打字稿 火力基地 Vue.js 谷歌云firestore vue-composition-api
