将updateProfile与Firebase身份验证结合使用时,displayName会被修剪

时间:2020-10-05 06:17:38

标签: javascript reactjs firebase authentication firebase-authentication

我正在使用Firebase身份验证createUserWithEmailAndPassword创建用户,并使用updateProfile方法更新用户的displayName。下面是我的代码。

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

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

用户单击“注册”按钮后将触发“注册”功能。用户名在控制台中正确显示。 enter image description here 创建用户后,还有另一个useEffect钩子将authUser登录到控制台

 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])

除了将displayName修剪掉以外,auth用户的属性似乎可以正常显示。 (“测试”应该是“测试”)。

The test was supposed to be testing

2 个答案:

答案 0 :(得分:0)

updateProfile的调用不会导致您的身份验证状态观察器的工作方式发生任何变化。实际上,如果您删除对updateProfile的调用,我相信日志将完全相同。 onAuthStateChanged将接收通过调用createUserWithEmailAndPassword创建的初始用户对象。也许您看到的是一个初始displayName值,该值仅包含电子邮件地址中“ @ gmail.com”之前的所有内容。

如果调用updateProfile,并且要观察displayName的变化,则应注销用户并重新登录以获取新的用户对象。或者,甚至更好的是,您可以将显示名称存储在数据库中,以便可以立即对其进行读写。

答案 1 :(得分:0)

我猜问题是因为updateProfile是异步的。将回调函数转换为异步函数后,displayName不再被修剪。

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