简体   繁体   中英

I cannot save data to the database after creating user authentication

I cannot save data to the database after creating user authentication on firebase, the following error appears on the console: "TypeError: firebase.auth (...). CurrentUser is null". it seems that the code cannot read the user's uid after creating the authentication

the code:

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

what needs to be changed so that the code can read the user's uid and save the data in the database?

You're not waiting until the new user creation process is complete before writing the database. createUserWithEmailAndPassword returns a promise which resolves when the work is done. It will give you a UserCredential object to work with.

firebase.auth().createUserWithEmailAndPassword(emailInput.value, passwordInput.value)
.then(userCredential => {
    // write the database here
})
.catch(error => {
    // there was an error creating the user
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM