我想知道,為什么我可以使用addDoc將資料寫入 Firestore而無法使用onSnapshot()
// CheckoutForm.js
import { addDoc, setDoc, doc, onSnapshot, collection, getDoc } from "firebase/firestore";
import { firestore } from "../../firebase";
import { getStripe } from "./initializeStripe";
export async function createCheckoutSession(uid) {
// Create a new checkout session in the subollection inside this users document
await addDoc(collection(firestore, "users", `${uid}`, "checkout_sessions"), {
price: "price_1M0jbXFlIMqx6x27XApjUcnp",
success_url: window.location.origin,
cancel_url: window.location.origin,
})
// Wait for the CheckoutSession to get attached by the extension
onSnapshot(doc(firestore, "users", `${uid}`, "checkout_sessions"), (doc) => {
console.log("Current data: ", doc.data());
const { sessionId } = doc.data();
if (sessionId) {
const stripe = await getStripe();
stripe.redirectToCheckout({ sessionId });
}
});
}
所以這給我一個錯誤:
未處理的承諾拒絕:FirebaseError:無效的檔案參考。檔案參考必須有偶數個段,但 users/XQRo8Mn0k7awkxCYPTQ7IeWHID93/checkout_sessions 有 3
在我得到一些相同的東西之前,當嘗試用 寫入資料時setDoc,我仍然不明白為什么我不能這樣做,現在和 一樣onSnapshot(),需要一些確切數量的路徑。當我使用addDoc給 doc random id 寫入資料時,我無法進入它。
我會很高興得到幫助!
馬克西姆
uj5u.com熱心網友回復:
正如錯誤所暗示的,您的檔案路徑中有 3 個段指向集合而不是檔案。在這里,您可以從結果中獲取新創建檔案的 IDaddDoc并使用 in onSnapshot,如下所示:
const docRef = await addDoc(collection(firestore, "users", `${uid}`, "checkout_sessions"), {
price: "price_1M0jbXFlIMqx6x27XApjUcnp",
success_url: window.location.origin,
cancel_url: window.location.origin,
})
// Wait for the CheckoutSession to get attached by the extension
onSnapshot(doc(firestore, "users", `${uid}`, "checkout_sessions", docRef.id), (doc) => {
console.log("Current data: ", doc.data());
// ...
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/531301.html
標籤:Google Cloud Collective javascript反应火力基地谷歌云火库
