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

时间:2019-12-23 04:51:16

标签: reactjs firebase react-native firebase-authentication react-native-android

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

我正在使用docs(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仍返回null。

请帮助。

1 个答案:

答案 0 :(得分:1)

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

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