0
votes

I was using firebase authentication createUserWithEmailAndPassword to create a user and used the updateProfile method to update the displayName of the user. Below is my code.

   const signUp = (event) => {
    event.preventDefault();
    console.log(username);

    auth.createUserWithEmailAndPassword(email,password)
    .then((authUser)=>{
      authUser.user.updateProfile({
        displayName : username
      })
    })
    .catch(err=>alert(err.message));
  }

The signUp function get triggered upon the user clicking the signUp button. The username display correctly in the console. enter image description here After creating user, there is another useEffect hook to log the authUser to console

 useEffect(()=>{
    const unsubscribe = auth.onAuthStateChanged((authUser)=>{
      if(authUser){
        //user has login...
        console.log(authUser);
        setUser(authUser);
        if(authUser.displayName){
          //dont update username
        }else{
          return authUser.updateProfile({
            displayName : username,
          })
        }
      }else{
        //user has logged out...
        setUser(null);
      }

      return () => {
        //perform some cleanup actions
        unsubscribe();
      }
    })
  },[user,username])

The properties of the auth user seems to be displayed all fine except the displayName was trimmed. (The "test" was supposed to be "testing").

The test was supposed to be testing

2

2 Answers

0
votes

The call to updateProfile won't cause any changes to the way that your auth state observer works. In fact, if you remove the call to updateProfile, I'm certain that the log will be exactly the same. onAuthStateChanged is going to receive the initial user object that's created by the call to createUserWithEmailAndPassword. Perhaps what you are seeing is an initial displayName value that simply contains everything before "@gmail.com" in the email address.

If you call updateProfile, and you want to observe the changes in displayName, you should sign out the user and sign them back in to get a new user object. Or, even better, you can store the display name in a database so you can read and write it instantly.

0
votes

I guess the problem was because the updateProfile is asynchronous. The displayName did not get trimmed anymore after I've converted the callback function into an async function.

const signUp = (event) => {
    event.preventDefault();
    console.log(username);
    auth.createUserWithEmailAndPassword(email, password)
      .then(async (authUser) => {
        await authUser.user.updateProfile({
          displayName: username,
        })
      })
      .catch(err => alert(err.message));

    setOpen(false);
  }