简体   繁体   中英

How to get user uid and print it outside the auth function

Please help me i want to get the user UID and save it in a global variable and use it wherever required i am using this method but its not working

'''

var userUID= null;

firebase.auth().onAuthStateChanged(function(user){
  if(user){
      console.log("logged in");
      userUID=firebase.auth().currentUser.uid;
      console.log(userUID);  //This statement is printing properly

    }
  else{
      console.log("Not Logged In");
  }
});


  console.log(userUID); // This statement is returning null (i want this to work)

'''

The problem here is that Firebase takes some time to log in automatically. While it's waiting to log in, onAuthStateChanged will not be called, and userUID will still be null when JS proceeds on to execute console.log(userUID) .

Unfortunately, the real solution to this is to change your app's structure to be able to handle a null userUID . It's likely that it is possible for a non-logged-in user to browse this page, and therefore it probably needs to be handled anyway. There are two ways to do this:

  1. Manually check if userUID is null, and disable features based on that;
  2. Change your code to execute only after onAuthStateChanged is called, so that your code is always executed with a valid userUID . This can be done with Promises or callbacks as you desire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM