简体   繁体   中英

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?

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

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