【问题标题】:Using firebase authentication and firestore to add user使用 firebase 身份验证和 firestore 添加用户
【发布时间】:2021-06-11 19:53:43
【问题描述】:

我正在尝试使用用户对 firebase 和 firestore 进行身份验证。当我点击 Save 时,SavePress 功能被激活。我第一次单击此按钮时,用户被添加到 firebase 身份验证,但用户等于 null。只有在第二次它的工作。 如果有人可以帮助我..

这是我的代码:

SavePress=async()=>{
      
    if(this.state.email==="" || this.state.password==="" || this.state.firstname==="" || this.state.lastname==="" || this.state.confirmpassword==="" || (this.state.status===""))
    {
      alert("All fields are required")
    }
    else{
            await firebase.auth().createUserWithEmailAndPassword(email,password)
            .then(
                firebase.auth().onAuthStateChanged(user=>
                {
                    console.log("user : ",user)
                    if(user!=null)
                    {
                        firebase.firestore().collection("Users").doc(firebase.auth().currentUser.uid)
                        .set({firstname,lastname,email,status})
                        .then(this.checkStatus(status,{user}))
                    }
                })
            )
            .catch((error)=>
            {
                console.log(error.code);//revoir cette erreur
                if(error.code == "auth/email-already-in-use")
                    {alert("User already exists. Try to log in")}
            })
}
}

【问题讨论】:

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


    【解决方案1】:

    当您登录 firebase 时,firebase auth 需要时间来更改 auth,因此,您在第一次按下时会得到一个空值。您需要使用侦听器来更改身份验证。

    firebase.auth().onAuthStateChanged(user => {
       if(user){
        // add user to firestore database.   
       }
     })
    

    【讨论】:

    • 但是当我使用“.then(..)”时,它不是监听器?
    • then() 在登录没有错误时调用,但这并不意味着 firebase auth 不为空。要确认 firebase.auth() 填充了当前用户,请尝试上面的代码。
    【解决方案2】:

    除了 Aymen 的回答,您实际上不需要在 then() 回调中使用 onAuthStateChanged。由于在成功创建用户时会调用then() 回调,因此您可以这样做:

    firebase.auth().createUserWithEmailAndPassword(email,password).then((credentials) => {
        const user = credentials.user;
        firebase.firestore().collection("Users").doc(firebase.auth().currentUser.uid)
        .set({firstname,lastname,email,status})
        .then(this.checkStatus(status,{user}))
    ).catch((error)=>{
        console.log(error.code);//revoir cette erreur
        if(error.code == "auth/email-already-in-use")
            {alert("User already exists. Try to log in")}
    })
    

    【讨论】:

    • 我试过了,但它说变量 user 没有定义..
    • 啊,确实不一样。我更新了我的答案以显示如何从 then() 处理程序获取用户。
    猜你喜欢
    • 2020-01-27
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 2019-08-13
    • 2021-05-29
    • 2018-08-18
    • 2021-07-31
    相关资源
    最近更新 更多