【问题标题】:displayName from firebase returns null untill I refresh the app one time来自firebase的displayName返回null,直到我刷新应用程序一次
【发布时间】:2021-04-20 08:32:08
【问题描述】:

我正在运行一个 React Native 项目,并使用 Firebase 作为我的数据库。我做了一个注册页面,从用户那里获取电子邮件、用户名和密码。我使用了 SignUpWithEmailAndPassword 函数,之后我使用更新配置文件并将用户名输入添加为 displayName 值:

firebase
        .auth()
        .createUserWithEmailAndPassword(email, password)
        .then((res) => {
          console.log(res);
          firebase.firestore().collection("users").add({
            email: email,
            username: username,
            password: password,
          });
          firebase.auth().currentUser.updateProfile({
            displayName: username,
            photoURL: "",
          });
          console.log(firebase.auth().currentUser.displayName);

现在显示名称已保存,但在我刷新一次之前它不会更新它的值。因此,console.log 在用户提交信息后返回 null 而不是显示名称。这里有什么问题?

【问题讨论】:

  • createUserWithEmailAndPassword 返回一个 Promise 并且当 Promise 挂起时您正在控制台记录,请尝试使用 async/await
  • Jad Alhamwi,我该怎么做?该函数在箭头函数中,我是否将箭头函数更改为异步函数?
  • 如下:async() => { ‘body’},并在body中为promise添加await

标签: javascript firebase-authentication


【解决方案1】:

正如 Jad Alhamwi 所说,这是异步/等待的问题

updateProfil 方法返回 Promise,所以你必须等待这个分辨率才能显示displayName

https://firebase.google.com/docs/reference/js/firebase.User#updateprofile

firebase
        .auth()
        .createUserWithEmailAndPassword(email, password)
        .then(async (res) => {
          console.log(res);
         
         firebase.firestore().collection("users").add({
            email: email,
            username: username,
            password: password,
          });
          
          await firebase.auth().currentUser.updateProfile({
            displayName: username,
            photoURL: "",
          });
          
          console.log(firebase.auth().currentUser.displayName);
        })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 2016-10-06
    • 2021-08-23
    • 1970-01-01
    • 2020-02-04
    • 2021-11-01
    • 2015-08-31
    • 1970-01-01
    相关资源
    最近更新 更多