displayName returns null when createUserWithEmailAndPassword Firebase React

Advertisements

I have a small React app and I want to make a Firebase registration functionality with adding a username in registration. Registration is successful, but adding a username does not work, I get null in displayName.

  const createUser = (email, password, username) => {
    updateProfile(auth.currentUser,{
      displayName: username
    })
   return createUserWithEmailAndPassword(auth, email, password,username);
  };

Signup page

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [username, setUsername] = useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");
    if (validPass) {
      try {
        await createUser(email, password, username);
        navigate("/account");
        setNoUser(false);
      } catch (e) {
        setError(e.message);
      }
    } else {
      setWrongPassword(true);
    }
  };

<form onSubmit={handleSubmit}>
   <div>
   <label>Username</label>
    <input
      onChange={(e) => setUsername(e.target.value)}
      type="text"
      placeholder="place for username"
      required
     />
    </div>
    <div>
     <label>Email Address</label>
     <input
       onChange={(e) => setEmail(e.target.value)}
       type="email"
       placeholder="place for email"
       required
      />
     </div>
  //Here is the rest of the code that works
  </form>

>Solution :

The order of API calls here is wrong:

const createUser = (email, password, username) => {
  updateProfile(auth.currentUser,{
    displayName: username
  })
 return createUserWithEmailAndPassword(auth, email, password,username);
};

You can only call updateProfile once the account has been created, but you call it before calling createUserWithEmailAndPassword.

What you’ll want to do is:

const createUser = (email, password, username) => async {
  const result = await createUserWithEmailAndPassword(auth, email, password,username)
  updateProfile(auth.currentUser,{
    displayName: username
  })
  return result;
};

Note that the updateProfile may not immediately update the data in currentUser. So if you want to show the result right away, you’ll want to reload the profile after updating it.

const createUser = (email, password, username) => async {
  const result = await createUserWithEmailAndPassword(auth, email, password,username)
  await updateProfile(auth.currentUser,{
    displayName: username
  })
  await auth.currentUser.reload();
  return result;
};

Leave a ReplyCancel reply