1

I'm trying to get my current user after the login, but this returning null. There's my code:

var currentUser;
firebase
    .auth()
    .onAuthStateChanged(function(user){
        currentUser = user;
        console.log(currentUser); //this returns my user object 
    });
console.log(currentUser); //this returns "undefined"

var otherCurrentUser = firebase.auth().currentUser;
console.log(otherCurrentUser); // this returns "null"
KENdi
  • 7,576
  • 2
  • 16
  • 31

2 Answers2

2

The onAuthStateChanged event fires whenever the user's authentication state changes. The user variable is only useful within that callback. You cannot transport it out of that function.

So all code that requires a user should be inside the callback:

var currentUser;
firebase
    .auth()
    .onAuthStateChanged(function(user){
        currentUser = user;
        console.log(currentUser); //this returns my user object 
    });

For more on this, see some of these:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I want to use the currentUser or other function of firebase out of own function. I've tried the `firebase.auth().currentUser`, but it returns null. Did have one way to get the currentUser, after the login, out of this? – Victor Lucas Jun 23 '17 at 04:16
2
var otherCurrentUser = firebase.auth().currentUser;

This will return null because auth object has not been initialized, you need an observer to do that. While Login, use observer and save the UID in localstorage, and while logout clear the localstorage

Observer

var currentUser;
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
      currentUser = user.uid;
      console.log(currentUser); //this returns my user object 
      window.localStorage.setItem("UID",currentUser);
  } else {
      currentUser = "Error"
      console.log(currentUser); //this returns my user object 
      window.localStorage.setItem("UID",currentUser);
       alert(" Error in your login code");
    // No user is signed in.
  }
});

After this, whenever you need to get the user id, just use

var getuid = window.localStorage.getItem("UID")
console.log(getuid) // will log the UID

While logout just remove it

window.localStorage.removeItem("UID");

Hope this helps..!

Prags
  • 811
  • 5
  • 17