Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can write, but can't read Firestore doc

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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());
  // ...
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading