React-Native - 无法将 displayName 和 photoURL 保存到 firebase

React-Native - Unable to save displayName and photoURL to firebase

我发现在我的 React Native 项目中注册时很难将用户的 displayName 和 photoURL 保存到 firebase。

我正在使用文档 (https://firebase.google.com/docs/reference/js/firebase.User.html#updateprofile) 作为指南。

看下面我的代码:

  onRegister = () => {
  firebase.auth().createUserWithEmailAndPassword( this.state.typedEmail, this.state.typedPassword)
  .then((userCredentials) => {
    if(userCredentials.user) {
      console.warn(userCredentials.user)
      userCredentials.user.updateProfile({
        displayName: "Jane Q. User",
        photoURL: "https://example.com/jane-q-user/profile.jpg"
      })
      .then(() => {
        this.setState({ user: userCredentials.user })
        console.warn("yo:", this.state.user)
      })
    }
  }).catch((error) => {
      console.warn(`error:, ${error}`)
  })}

使用上述功能我可以保存电子邮件和密码,但 displayName 和 photoURL 仍然 returns null。

请帮忙。

您可以尝试重新加载然后获取当前用户

async function updateProfile() {
  await firebase.auth().currentUser.updateProfile({
        displayName: "Jane Q. User",
        photoURL: "https://example.com/jane-q-user/profile.jpg"
      });
  await firebase.auth().currentUser.reload();
  console.log(firebase.auth().currentUser.displayName); <-- check if it is updated
}

更新

onRegister = async () => {
  try {
    const userCredentials = await firebase
      .auth()
      .createUserWithEmailAndPassword(this.state.typedEmail, this.state.typedPassword);
    if (userCredentials.user) {
      console.warn(userCredentials.user);
      await userCredentials.user.updateProfile({
        displayName: 'Jane Q. User',
        photoURL: 'https://example.com/jane-q-user/profile.jpg',
      });
      await userCredentials.user.reload();
      this.setState({ user: firebase.auth().currentUser });
      console.warn('yo:', this.state.user);
    }
  } catch (error) {
    console.warn(`error:, ${error}`);
  }
};