Q:

Creating Firebase User and simultaneously adding data into database

I want to have my create users to be added into my database by their user uid when i sign them up from my firebase.
currently my code is working , just i dont understand why when my data is save into my firebase, the name (which is suppose to be the created user uid) shows "undefined". but the data that is grabbed and saved is correct. 
My firebase database which shows undefined:  https://imgur.com/ATRsmKe
My JS code which i am trying to save and create user: 
/*Show Login User*/

// Firebase Variables
var auth = firebase.auth();

$(document).ready(function () {

  //Pass parameter from form to Firebase
  $('.addpic').on('submit', event => {
    event.preventDefault();
    const name = $('#name').val();
    const hp = $('#hp').val();
    const email = $('#email').val();
    const password = $('#password').val();
    const role = $('#role').val();

    //Firebase user authentication
    firebase.auth().createUserWithEmailAndPassword(email, password)
      .then(user => {

        //set data into User database
        firebase.database().ref('Admin/Person In Charge' + "/" + user.uid).set({
          Name: name,
          ContactNo: hp,
          Email: email,
          Password: password,
          Role: role
        }).then(success => {
          console.log(user);
          window.alert("Registered");
          window.location = "user.html";
        });
      })
      .catch(function (error) {

        var errorCode = error.code;
        var errorMessage = error.message;

        window.alert("Error : " + errorMessage);
      });
  });
});

I want my data to be saved under the UID of the created user. I tried all possible solutions, but none work for me. 

A:

You should take a look at the return type of createUserWithEmailAndPassword. If I'm reading the docs correctly, it returns an instance of firebase.auth.UserCredential, not an actual user. I think you need to actually drill down one more level into that credential object and get the user.uid.
Example
firebase.auth().createUserWithEmailAndPassword(email, password)
  .then(userCredential => {

    //set data into User database
    firebase.database().ref('Admin/Person In Charge' + "/" + userCredential.user.uid).set({
      Name: name,
      ContactNo: hp,
      Email: email,
      Role: role
    }).then(success => {
      console.log(user);
      window.alert("Registered");
      window.location = "user.html";
    });
  })

You could figure this out in the future by inspecting the value of your user in your then via a console.log().

