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"
3
  • look at this option may be it helps link Commented Jun 23, 2017 at 3:21
  • I have tried, but doesn't work for me Commented Jun 23, 2017 at 3:38
  • 1
    solved in stackoverflow.com/a/50684239/1356559 Commented Dec 4, 2021 at 0:57

2 Answers 2

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..!

Sign up to request clarification or add additional context in comments.

2 Comments

does your browser support localStorage
It works for me: localStorage.getItem('currentUid');
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:

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.