d-dripz
d-dripz

Reputation: 85

FirebaseError: Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: undefined

I'm creating an email account in firebase in my register function, and then creating a profile collection to store profile information such as profile image, firstName, lastName, etc.

Currently, I receive this error when I click on the register button:

FirebaseError: Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: undefined```

I believe this is happening because firebase hasn't created the users collection fast enough and when I try to create the profile collection, it renders the error because it can't locate the users collection.

Should I be using an async function?

function Register() {
  const history = useHistory();
  const [email, setEmail] = useState("");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [image, setImage] = useState("");
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [user, setUser] = useState("");

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

    auth
      .createUserWithEmailAndPassword(email, password)
      .then((auth) => {
        // it successfully created a new user with email and password
        if (auth) {
          history.push("/dashboard");
        }
      })
      .catch((error) => alert(error.message));

    db.collection("users").doc(user?.uid).collection("profile").add({
      image: image,
      firstName: firstName,
      lastName: lastName,
      username: username,
    });
  };

Upvotes: 1

Views: 725

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317322

Here's the line of code where you call doc():

db.collection("users").doc(user?.uid).collection("profile").add({

Note that you are possibly passing undefined to doc(). That will happen if user is null or undefined. This is likely because createUserWithEmailAndPassword is asynchronous and doesn't complete immediately. If you want to do something after the account is created, you should do that within your then callback.

    auth
      .createUserWithEmailAndPassword(email, password)
      .then((credential) => {
        db.collection("users").doc(credential.user.uid).collection("profile").add({
          image: image,
          firstName: firstName,
          lastName: lastName,
          username: username,
        });
        history.push("/dashboard");
      })

Upvotes: 1

Related Questions