Home > OS >  Firestore Document reference is always undefined in react native
Firestore Document reference is always undefined in react native

Time:10-18

I'm new to React Native and Firestore. I can't figure out why my document reference id keeps coming up as undefined in my console log, but there's an id in the Firestore database. I'm just trying to capture the id so that I can use it on another screen and add more fields to the document. Here is a sample of my code:

    const handleSignUp = () => {
createUserWithEmailAndPassword(auth, email, password)
  .then((userCredentials) => {
    const user = userCredentials.user;
    console.log("Registered with: ", user.email);
    console.log("Welcome", name);
    try {
      const docRef = addDoc(collection(db, "userInfo"), {
        fullname: name,
        userID: uID,
      });
      console.log("Success writing document!", docRef.id, "yay");
    } catch (e) {
      console.error("Error adding document: ", e);
    }
  })
  .catch((error) => alert(error.message));

};

CodePudding user response:

Since addDoc returns a promise you need to use await or then.

      const handleSignUp = () => {
createUserWithEmailAndPassword(auth, email, password)
  .then(async (userCredentials) => { // make function async
    const user = userCredentials.user;
    console.log("Registered with: ", user.email);
    console.log("Welcome", name);
    try {
      const docRef = await addDoc(collection(db, "userInfo"), { // here you need to use await
        fullname: name,
        userID: uID,
      });
      console.log("Success writing document!", docRef.id, "yay");
    } catch (e) {
      console.error("Error adding document: ", e);
    }
  })
  .catch((error) => alert(error.message));

More info on google docs : https://firebase.google.com/docs/firestore/manage-data/add-data#add_a_document

  • Related