首页 > 解决方案 > 为什么 displayName 没有得到更新?使用 onAuthChanged

问题描述

我正在使用 Redux 并坚持我的身份验证。onAuthChanged使用 redux 工具包,我有一个从 Firebase Auth进行检查的操作。

export const persistedSession = () => {
  return async (dispatch) => {
    dispatch(requestLogin());
    firebaseAuth.onAuthStateChanged(async (user) => {
      if (user) {
        const currentUser = await createUserProfileDocument(user);
        currentUser.on("value", (snapshot) => {
          var data = snapshot.val();
          if (data !== null) {
            //Success
          }
        });
      }
    });
  };
};

然后,当我检查该用户是否存在文档时,如果不存在则创建一个。

export const createUserProfileDocument = async (user) => {
  if (!user) return;

  const { uid, displayName, email } = user;
  const userReference = database.ref("users");
  userReference.once("value", (snapshot) => {
    if (!snapshot.hasChild(uid)) {
      userReference.child(uid).set({
       ...
      });
    }
  });
  return userReference;
};

所以这就是我的问题所在。创建我的用户时displayName始终为空,如何正确更新用户配置文件?似乎onAuthChanged在它可以进行更新之前被触发,因此 displayName 将始终为 null 并且文档将不包含 displayName 属性

export const registerUser = (value) => {
  const { firstName, surname, email, password } = value;
  return async (dispatch) => {
    
    firebaseAuth
      .createUserWithEmailAndPassword(email, password)
      .then(async (result) => {
        const user = result.user;
        user.updateProfile({
            displayName: `${firstName} ${surname}`,
          })
         
      })
      .catch((error) => {
        console.log("Unable to create user profile: ", error);
      });
  };
};

标签: javascriptreactjsfirebase-realtime-databasereduxfirebase-authentication

解决方案


调用updateProfile不会触发onAuthStateChanged,因为身份验证状态不会改变。也无法延迟onAuthStateChanged此处的触发,因为您只能在创建用户帐户后设置显示名称,这也将其登录。

我能想到的两个选择:

  1. 创建用户,设置其显示名称,将其注销,然后再次登录。然后后者将触发另一个onAuthStateChanged 包含显示名称的内容。

  2. 当您还调用updateProfile.


推荐阅读