【问题标题】:Firebase Cannot read property 'uid' of nullFirebase 无法读取 null 的属性“uid”
【发布时间】:2020-06-27 08:26:32
【问题描述】:

由于某种原因,firebase 无法读取属性 UID。任何帮助将不胜感激!我应该首先改变从 firebase.auth 获取数据的方式吗?最终目标是使用用户 UID 的 ID 更新 firestore 数据库文件。

    // Add additional info to user account
const completeAccountform = document.querySelector('#wf-form-completeAccount');
document.getElementById("completeButton").addEventListener('click', addAccountinfo);

function addAccountinfo() {
    // get new account data
    const firstName = completeAccountform['firstName'].value;
    const lastName = completeAccountform['lastName'].value;
    const location = completeAccountform['location'].value;

    const db = firebase.firestore();
    firebase.auth().currentUser.uid;
        db.collection('users').doc(user.uid).set({
            email: signupForm['signupEmail'].value,
            firstname: completeAccountform['firstName'].value,
            lastname: completeAccountform['lastName'].value,
            location: completeAccountform['location'].value
    }).then(function(docRef) {
        modalContainer.style.display = 'none'
        console.log("Document updated with ID: ", docRef.id);
    })
    .catch(function(error) {
        console.error("Error updating document: ", error);
    });

    form.reset()
};

【问题讨论】:

    标签: javascript google-cloud-firestore firebase-authentication


    【解决方案1】:

    我建议您按照我指定的方式按照Firebase docs 的建议检索当前用户:

    获取当前用户的推荐方法是设置观察者 在 Auth 对象上:

    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
      } else {
        // No user is signed in.
      }
    });
    

    通过使用观察者,您可以确保 Auth 对象不在 中间状态——比如初始化——当你得到当前的 用户。当您使用 signInWithRedirect 时,onAuthStateChanged 观察者 等到 getRedirectResult 解决后再触发。

    我建议你使用观察者,因为有时 auth 对象还没有完成初始化并且它会为空(然后你会遇到这个错误)。这取决于您的身份验证流程以及更适合您的用户案例的方式

    【讨论】:

    • 感谢@chinoche!解决了我的问题!在填充 UID 之前,我正在调用一个函数来从数据库中获取用户信息!我已经有一个名为 handleAuthStateChanged 的​​函数,它使用了 onAuthStateChanged,但我基本上是在尝试在两个地方获取用户信息,而它应该刚刚在 handleAuthStateChanged 中。再次感谢!
    猜你喜欢
    • 2018-11-06
    • 1970-01-01
    • 2021-06-19
    • 2019-02-05
    • 2019-02-14
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多