0

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));

};

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.