我正在嘗試獲取其中有多少檔案firestore以獲取當天的相關檔案,然后使用 React 保存新檔案。出于某種原因,當我執行保存新檔案的函式時,會導致firestore在無限回圈中添加新記錄。可能我做錯了什么。有人可以指出我的錯誤嗎?
這是我保存新檔案的功能。
import { db } from '../utils/init-firebase'
import { collection, query, onSnapshot, Timestamp, addDoc, where } from "firebase/firestore"
export interface ProjectState {
projectId: string,
name: string;
}
const saveProject = async (project: ProjectState) => {
try {
const today = Timestamp.fromDate(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()));
const q = query(collection(db, 'projects'), where('created', '>=', today));
let count = 0
const unsubscribe = onSnapshot(q, (querySnapshot) => {
count = querySnapshot.docs.length 1;
const date = new Date();
const month = twoDigitDate(date.getMonth() 1);
const day = twoDigitDate(date.getDate());
const year = date.getFullYear().toString().slice(-2)
const projectId = `${month}${day}${year}${count > 0 ? '-' count : ''}`;
const projectDoc = collection(db, 'projects');
return addDoc(projectDoc, {
projectId,
name: project.name
created: Timestamp.now(),
});
})
} catch (err) {
console.log('Error creating project:', err)
}
}
const twoDigitDate = (date: number) => {
return date < 10 ? `0${date}` : date;
}
export default saveProject;
uj5u.com熱心網友回復:
您有無限回圈,因為onSnapshot()偵聽器一直在偵聽收集,并且當新檔案出現時再次觸發快照中的所有檔案 您添加的一個額外檔案。安裝onSnapshot()使用getDocs()功能。
import { collection, query, where, getDocs } from "firebase/firestore";
const q = query(collection(db, "cities"), where("capital", "==", true));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
你的功能應該是這樣的嗎?
const saveProject = async (project: ProjectState) => {
try {
const today = Timestamp.fromDate(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()));
const q = query(collection(db, 'projects'), where('created', '>=', today));
let count = 0
const querySnapshot = await getDocs(q)
querySnapshot.forEach(doc => {
// your code what ever you want to do.
})
} catch (err) {
console.log('Error creating project:', err)
}
}
我不知道您為什么要根據此集合中的舊檔案在同一集合中制作新檔案。您需要記住只使用您現在使用的查詢,您將獲得最多 100 個檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/417646.html
標籤:
上一篇:Javascript-forEach與promise.all不起作用
下一篇:我如何在打字稿反應中匯入svg
