Home > Mobile >  Firebase Auth createUserWithEmailAndPassword in React app
Firebase Auth createUserWithEmailAndPassword in React app

Time:08-31

I am having some issues with Firebase Auth creating a user in my react app.

The other functions, sign-in, sign-out, password reset all work fine with the same Firebase account. Just sign up isn't working.

I have a form on the sign up page which when submitted does the following:

  const onSubmit = (e) => {
    e.preventDefaualt();
    const email = emailRef.current.value;
    const name = nameRef.current.value;
    const password = passwordRef.current.value;
    if(email && name && password) registerUser(email, name, password);
  };

This then starts this:

    const registerUser = (email, name, password) => {
        const id = user.userUID
        setLoading(true);
        setUID(id);
        createUserWithEmailAndPassword(auth, email, password)
        .then(() => {
            return updateProfile(auth.currentUser, {
                displayName: name,
                email: email,
                userUID: id
            });
        })
        .then((res) => console.log(res))
        .then(() => (window.location.pathname = `/subscriptions`))
        .catch((err) => setError(err.message))
        .finally(() => setLoading(false));

My understanding is that this should create a new user in firebase?

CodePudding user response:

The updateProfile() can be used to update displayName and photoURL only. If you want to update email then you must use updateEmail(). However, that's not required here as you are creating user account with same email.

Try refactoring the code as shown below:

const onSubmit = (e) => {
  e.preventDefault();
  const email = emailRef.current.value;
  const name = nameRef.current.value;
  const password = passwordRef.current.value;

  if (email && name && password) {
    registerUser(email, name, password).then(() => {
      console.log("User created")
    })
  };
};


const registerUser = async (email, name, password) => {
  try {
    console.log("> Registering user")
    setLoading(true);
    const {
      user
    } = await createUserWithEmailAndPassword(auth, email, password)

    console.log("> Updating profile")
    await updateProfile(user, {
      displayName: name,
    });

    window.location.pathname = `/subscriptions`;
  } catch (e) {
    console.log(e)
  }

  setLoading(false)
}

You cannot update user's UID once created. If you want to set a custom UID to user while creating then you need to use the Admin SDK. Checkout: Custom Uid In Firebase CreateUser

  • Related