0

After creating new user with auth.createUserWithEmailAndPassword and updating profile, firebase auth listener (onAuthStateChanged) showing displayName in user object but it is not accessible. Uploading screenshots of this behavior as well as code.

null - displayName displayName can be seen on expanding object

  export var signup = userData => {
    return async dispatch => {
    try {
    var { username, email, password } = userData;
    var createdUser = await auth.createUserWithEmailAndPassword(
      email,
      password
    );
    //updating auth profile
    await createdUser.user.updateProfile({
      displayName: username,
      email: email
    });
    //storing user info in firestore
    var userObj = {
      username: username,
      email: email,
      joinedAt: serverTimestamp()
    };
    await firestore
      .collection("users")
      .doc(`${createdUser.user.uid}`)
      .set(userObj);
    //setting up auth state
    dispatch(
      setCurrentUser({
        username: username,
        uid: createdUser.user.uid
      })
    );
      } catch (error) {
       console.log(error.meesage)
      }
    };
  };

  componentDidMount =  () => {
     auth.onAuthStateChanged((user) => {
      if(user){
        console.log(user)
        console.log(user.uid)
        console.log(user.displayName);
        console.log(user.email)
      }
    })
   };
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Ahsan Khan
  • 21
  • 1
  • 3

1 Answers1

4

The auth state listener is going to trigger immediately after the user is created when you call createUserWithEmailAndPassword(). At that moment, the user will not have a displayName property. It's not until after you call updateProfile() that the account will have a displayName. However, the call to updateProfile() will not trigger the auth state listener again. You should instead maintain your own record, in memory or in some database, of the name that you added with updateProfile(), and use that value later.

The user object delivered to the auth state listener will not see the new value of displayName until the user signs out and back in again.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • 1
    When im calling console.log(user) ,display name is available there but when im calling console.log(user.displayName) it shows me null – Ahsan Khan Mar 03 '20 at 14:21
  • Yes, I understand. Please read my answer again - I explain how it works. – Doug Stevenson Mar 03 '20 at 15:57
  • @AhsanKhan The fact that you get null when doing `console.log(user.displayName)` but you see a non-null value in the Object tree displayed in the console is because the value is being dynamically-evaluated at the moment of expanding the Object tree. See https://areknawo.com/how-to-properly-log-objects-in-javascript/ and also https://stackoverflow.com/a/17547032/3371862. – Renaud Tarnec Oct 03 '20 at 16:58