0

Hello I am trying to capture the const user UID and console log it but for some reason, it cannot be pulled and is saying that the const is not defined

Here is my JS

function userIdShown() {
  firebase.auth().onAuthStateChanged(function userIdentification(user) {
  if(user){
    const userID = user.uid;

    return userID
  }
  });
}

userIdShown();

console.log(userID);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Jaffer Abyan Syed
  • 129
  • 1
  • 2
  • 11
  • Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Nick Jan 08 '19 at 01:06
  • https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – epascarello Jan 08 '19 at 14:15

2 Answers2

2

const variables are only visible inside the block where they are defined. In your case, that's only during the invocation of the callback function that you passed to onAuthStateChanged. It will not be visible outside that callback. I would also suggest that you not try to store it globally. Instead, at any point, you can simply use firebase.auth().currentUser to find out if someone is logged in, and what their user id is.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • I tried doing that but the documentation would not let me pull the current user info – Jaffer Abyan Syed Jan 08 '19 at 01:08
  • I don't understand what that means: "pull the current user info". If a user is logged in, currentUser is user object, and it contains information about the currently logged in user, including the uid. If a user is not logged in, currentUser will be null. It's in the API docs that I linked. – Doug Stevenson Jan 08 '19 at 01:08
  • but in terms of the documentation it specifically states something along the lines like `.currentUser().displayName` I am wondering where I would set displayName and other criteria such as that – Jaffer Abyan Syed Jan 08 '19 at 01:10
  • Now you're asking a completely different question than the one you started out with. If you have a new question, please ask it separately, otherwise these comments may go on indefinitely. – Doug Stevenson Jan 08 '19 at 01:11
1

I believe the issue is that you are trying to console log userID outside of where it's defined.

Try console logging userID here:

 if(user){
     const userID = user.uid;
     console.log('userID', userID)
     return userID
              }

Where you are console logging, it can't read the value of userID because it can't "see" it.