Home > Mobile >  firebase displayName not updating on the UI even though console says it was updated successfully in
firebase displayName not updating on the UI even though console says it was updated successfully in

Time:12-09

I am using Firebase Auth with my React app and when a new user signs up, his displayName won't show on the UI even though it was updated in the server, and even though the email and everything else shows on the UI like supposed. It's as if the UI loads before displayname has updated or something.

Can someone help me resolve this issue?

useEffect(
    () =>
        onAuthStateChanged(firebaseAuth, (user) => {
            if (user) {
                dispatch({
                    type: LOGIN,
                    payload: {
                        isLoggedIn: true,
                        user: {
                            id: user.uid,
                            email: user.email,
                            displayName: user.displayName,
                            emailVerified: user.emailVerified
                        }
                    }
                });
            } else {
                dispatch({
                    type: LOGOUT
                });
            }
        }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [dispatch]
);

 const firebaseRegister = async (displayName, email, password) => {
    await createUserWithEmailAndPassword(firebaseAuth, email, password).then((registeredUser) => {
        sendEmailVerification(firebaseAuth.currentUser);
        addDoc(collection(db, 'users'), {
            uid: registeredUser.user.uid,
            displayName,
            email,
            createdAt: serverTimestamp()
        });
    });
    console.log(firebaseAuth.currentUser);

    const user = firebaseAuth.currentUser;
    await updateProfile(user, { displayName })
        .then(() => {
            user.reload().then(() => console.log('Profile reloaded'));
        })
        .catch((err) => console.log(err));
};

CodePudding user response:

You should reload your user data after updating the profile:

user.updateProfile({ displayName }).then(() => {
  user.reload().then(() => {
    console.log('Profile reloaded');
  });
}).catch((error) => {
  console.log(error);
}); 

As a suggestion, migrate to firebase v9.

Update:

In order to show the updated user data in the UI, you should hold it in a state and not using auth.currentUser directly because when the currentUser gets updated, your component won't render again because it's not a state in your component:

const [firebaseUser, setFirebaseUser] = useState();
updateProfile(auth.currentUser, { displayName }).then(() => {
  auth.currentUser.reload().then(() => {
    console.log('Profile reloaded');
    setFirebaseUser(auth.currentUser);
  });
}).catch((error) => {
  console.log(error);
}); 
return(
  <div>
    /* ... */
      <div>{firebaseUser?.displayName}</div>
    /* ... */
  </div>
);
  • Related