Search code examples
firebaseauthenticationgoogle-cloud-firestoreuid

In Firestore, how do I determine the UID of the newly created user and set that UID as the document name?


Currently, I'm using the email as the document name but I'd like to use the UID instead. I tried using "firebase.auth().currentUser.uid" but that retrieves the UID from the last user.

try {
      setError("");
      setLoading(true);
      await signup(emailRef.current.value, passwordRef.current.value);
      await db
        .collection("users")
        .doc(emailRef)
        .set(
          {
            firstName: firstNameRef.current.value,
            lastName: lastNameRef.current.value,
          },
          { merge: true }
        )

Solution

  • I'm not sure about the function signup() and variables emailRef but you can try this. You can get the UID of newly created user from userCredential object.

    firebase.auth().createUserWithEmailAndPassword(email, password)
      .then(async (userCredential) => {
        // Signed in 
        const user = userCredential.user;
        await db.collection("users").doc(user.uid).set({
          firstName: firstNameRef.current.value,
          lastName: lastNameRef.current.value,
        }, { merge: true })
        // ...
      })
      .catch((error) => {
        var errorCode = error.code;
        var errorMessage = error.message;
        // ..
      });