Skip to content
Advertisement

firebase.auth().currentUser.uid showing previous uid

I’m trying to set user data into the realtime database. To do that I want the uid of the current user who is logged in. But when I use the firebase.auth().currentUser.uid; I’m getting the previous uid.

Here’s the code:

// Your web app's Firebase configuration
  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
  var firebaseConfig = {
    apiKey: "*",
    authDomain: "*",
    databaseURL: "*",
    projectId: "*",
    storageBucket: "*",
    messagingSenderId: "*",
    appId: "*",
    measurementId: "*"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);

//sign up the user
  const auth =  firebase.auth();
  var user_info_reference = firebase.database();

  document.getElementById('register-form').addEventListener('submit', submitInfo);

  //signup function
  const signupForm = document.querySelector('#register-form');
  signupForm.addEventListener('submit', (e) => {
    e.preventDefault();

    const email = signupForm['email_up'].value;
    const password = signupForm['pass_up'].value;


    //auth with firebase
    auth.createUserWithEmailAndPassword(email, password).then(cred => {
      console.log(cred.user);
      signupform.reset();
      user_id = firebase.auth().currentUser.uid;


    }).catch(function(error){

      var errorcode=error.code;
      var errormsg=error.message;
  
    });
  });

//saving user info
  //submitting info about name
function submitInfo(e){
    e.preventDefault();

    //get values
    var name = getInputval('name_up')
    saveInfo(name);

    //get id val
    function getInputval(id){
      return document.getElementById(id).value;
    }

function saveInfo(name){
      var new_user_info = user_info_reference.ref('user_info/'+ auth.currentUser.uid);
      new_user_info.set({
        name: name
      });
    }
  }

Don’t mind the (*) in the config, I just don’t want to show that information.

Advertisement

Answer

If you want to get the UID of the current user right after they signed in, you can get if from cred:

auth.createUserWithEmailAndPassword(email, password).then(cred => {
  user_id = cred.user.uid;
  ...
Advertisement