创建用户身份验证后,我无法将数据保存到数据库

在firebase上创建用户身份验证后,我无法将数据保存到数据库中,控制台上出现以下错误:“TypeError:firebase.auth (...)。当前用户为空”。创建身份验证后,代码似乎无法读取用户的 uid


代码:


createUserButton.addEventListener('click', function(){

firebase.auth().createUserWithEmailAndPassword(emailInput.value, passwordInput.value)

    var user = {

        nome: "Pedro",

        sobrenome: "Ribeiro",

        cpf: "946.201.340-31",

        uid: firebase.auth().currentUser.uid,

        email: emailInput.value,

        password: passwordInput.value

    }

    writeUserData(user)


.catch(function(error) {

// Handle Errors here.

     })

})


function writeUserData(user) {

    firebase.database().ref('users/' + firebase.auth().currentUser.uid).set(user).catch(error =>{

    console.log(error.message)

  })

}

需要更改哪些内容,以便代码可以读取用户的 uid 并将数据保存在数据库中?


收到一只叮咚
浏览 76回答 1
1回答

婷婷同学_

您不会等到新用户创建过程完成后再写入数据库。createUserWithEmailAndPassword 返回一个承诺,该承诺在工作完成后解析。它将为您提供一个要使用的 UserCredential 对象。firebase.auth().createUserWithEmailAndPassword(emailInput.value, passwordInput.value).then(userCredential => {    // write the database here}).catch(error => {    // there was an error creating the user})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript