I am trying to set the .displayName
property of a user, right after it is created.
The Problem:
The user needs some time to get created, so it would not work to use .updateProfile()
right after calling .createUserWithEmailAndPassword()
. So how can I eventually update the .displayName
right after the creation?
Right now I am trying this way:
export function signup(currentUser, email, password) {
createUserWithEmailAndPassword(auth, email, password)
updateProfile(currentUser, {displayName : "some name"})
}
When I am calling the function I use this function for the value of currentUser
export function useAuth() {
const [ currentUser, setCurrentUser ] = useState();
useEffect(() => {
const unsub = onAuthStateChanged(auth, user => setCurrentUser(user));
return unsub; // Cleaning Function
}, [])
return currentUser;
}
CodePudding user response:
Both the createUserWithEmailAndPassword()
and updateProfile()
methods are asynchronous and return a Promise. Therefore you either need to chain the Promises or use async/await
as mentioned by Scott in his comment.
1/ Chain the Promises
export function signup(currentUser, email, password) {
createUserWithEmailAndPassword(auth, email, password)
.then(userCredential => {
updateProfile(userCredential.user, {displayName : "some name"})
})
}
2/ Use async/await
export async function signup(currentUser, email, password) {
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
await updateProfile(userCredential.user, {displayName : "some name"})
}
CodePudding user response:
You need to call updateProfile(currentUser, {displayName : currentUser.displayName})
after currentUser have been updated by the useAuth hook
useEffect(() =>{
if ('userName' in currentUser && currentUser.userName !== '') {
updateProfile(currentUser, {displayName : currentUser.userName})
}
}, [currentUser])