mr.SoSerious
mr.SoSerious

Reputation: 121

Get user id after creating a user in firebase

I am trying to retrieve the id of the newly created user on my website. Admin creates the account based on the user's email and password. But as soon as the account is created, I need the id and use it in the firestore database as a document id to store user info. This is how my code looks:

firebase.auth().createUserWithEmailAndPassword(email.trim(), password.trim())
            .then(function () {
                db.collection("users").add({
                    email: email.trim(),
                    name: username.trim(),
                    id: //I need the user's id here
                }).then(function () {
                    window.alert('User registered successfully');
                    window.location = 'user.html';
                }).catch(function (error) {
                    window.alert("There was some error. Please try again.");
                    console.log(error.code);
                    console.log(error.message);
                });
            })

Is there a way that I can get that user's id in then part?

Upvotes: 1

Views: 2385

Answers (1)

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26288

You can try this:

firebase.auth().createUserWithEmailAndPassword(email, password)
.then((userCredential) => {  // the userCredential is a variable that will hold the response in it, it contains all the user info in it
    // Signed in
    var user = userCredential.user;
    // This user variable contains all the info related to user including its id
})
.catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
});

Reference

Upvotes: 2

Related Questions