Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call updateProfile() after creating User

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}

>Solution :

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"})   
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading