0

I am trying to retrieve a logged in users ID to retrieve information related to him from the database using firebase....

in my HTML page inside tags I have the following -

    var user
    var uid;
    firebase.auth().onAuthStateChanged(user => {
        if(!user) {
            window.location = 'login.html'; //If User is not logged in, redirect to login page
        } else {
            user = firebase.auth().currentUser;
            uid = user.uid;
        }
    });

    console.log("UID: " + uid);

and , it seems to be working in respect to checking if the user is logged in... because if I log in from main page and go to the page this is on it works and goes to the page, but if i go to the page when I am not logged in, it redirects to the login page...

however when i try to do that log statement it prints out uid as undefined... any idea why this is not working?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Chase
  • 267
  • 1
  • 6
  • 20
  • Where did you put the `console.log()`? – Frank van Puffelen Sep 18 '17 at 19:31
  • updated question – Chase Sep 18 '17 at 19:39
  • 2
    That is expected behavior. The code in your `onAuthStateChanged()` callback runs at a different time then the code around it. So `uid` will only have the correct value **inside** the callback. See https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function – Frank van Puffelen Sep 18 '17 at 19:45
  • yeah thats why i thought if I set a var I declared outside of the callback it would work... but no? guess your link will tell me how.. – Chase Sep 18 '17 at 19:55

1 Answers1

0

firebase promise will take some time to process the your business logic inside onAuhtStateChanged, So your consoles.log outside the promise will get invoked first and prints the UID as undefined before the onAuhtStateChanged promise is called, try to code like below

  var user
  var uid;
firebase.auth().onAuthStateChanged(user => {
    if(!user) {
        window.location = 'login.html'; //If User is not logged in, redirect to login page
    } else {
        user = firebase.auth().currentUser;
        uid = user.uid;
        _callPrintUserUID(uid)
    }
});

var _callPrintUserUID=function(uId){
   console.log("UID: " + uid);//print your global variable.
   console.log("UID: " + uId)// parameter passed.
}

I hope this helps you feel free to ask any doubts regarding this answer. See this answer, i have already answered the more similar question to yours

MuruGan
  • 1,402
  • 2
  • 11
  • 23