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>
2
Answers
You call
updateProfile()
before having created the user in the Firebase service, therefore it cannot work.You should first create the user and then update the profile, for example as follows:
The order of API calls here is wrong:
You can only call
updateProfile
once the account has been created, but you call it before callingcreateUserWithEmailAndPassword
.What you’ll want to do is:
Note that the
updateProfile
may not immediately update the data incurrentUser
. So if you want to show the result right away, you’ll want to reload the profile after updating it.