Using firebase authentication and firestore to add user

Viewed 560

Im trying to use user to the authentication of firebase and also firestore. Whhen I click on Save, the function SavePress is activated. The first time I click on this button, the user is added to firebase authentication but user is equal to null. Only at the second time it's work. If anyone can help me..

Here is my code :

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")}
            })
}
}
2 Answers

when you sign to firebase, firebase auth take time to change auth, for this reason, you got a null in the first press. you need to use a listener for auth change.

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

Alternatively to Aymen's answer, you actually don't need an onAuthStateChanged in your then() callback. Since the then() callback is called when the user has been successfully created, you can simply do:

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