1
votes

I am trying to create a document with an id that of the user as he signs up

this is the function which runs when user signs up ->

const register = (e) => {
    e.preventDefault();

    auth
      .createUserWithEmailAndPassword(email, password)
      .then((auth) => {
        if (auth) {
          db.collection("users").add({
            email: email,
            password: password,
          });

          history.push("/");
        }
      })
      .catch((error) => alert(error.message));
  };

Can anyone help me with how do I pass the .doc reference to accomplish this?

2

2 Answers

2
votes

Could you try the following code?

const register = e => {
  e.preventDefault();

  auth
    .createUserWithEmailAndPassword(email, password)
    .then(credential => {
      if (credential && credential.user) {
        db.collection("users")
          .doc(credential.user.uid)
          .set({
            email: email,
            password: password
          });

        history.push("/");
      }
    })
    .catch(error => alert(error.message));
};

See:

0
votes
await db
  .collection("users")
  .add({ name: "baibhav", gender: "male" })
  .then(async (docRef) => {
    const ref = db.collection("users").doc(docRef.id)
    ref
      .update({ car: "Ferrari" })
      .then(() => {
        // updated
        console.log("succeed")
      })
      .catch((err) => console.log(err))
  })
  .catch((err) => {
    console.log(err)
  })

You'd better use a ".add" method. it makes document id automatically. and You can use the document id after document fetched.

and toss the docRef.id to that wherever you have to use. and call the update method with the document id.