I am wondering, why can I write data to Firestore with addDoc and can't read that with 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 });
}
});
}
So that throw me an error:
Unhandled Promise Rejection: FirebaseError: Invalid document reference. Document references must have an even number of segments, but users/XQRo8Mn0k7awkxCYPTQ7IeWHID93/checkout_sessions has 3
Before I got some same, when trying write data with setDoc
, I still didn't get why I can't do it with that, and now the same with onSnapshot()
, that need some exactly number of paths.
When I'm writing data using addDoc
that give to doc random id so I can't get into it into.
I'll be glad for help!
Maksym
CodePudding user response:
As the error suggests, you have 3 segments in your document path that points to a collection and not a document. Here, you can get ID of the newly created document from the result of addDoc
and use in onSnapshot
as shown below:
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());
// ...
});