简体   繁体   中英

How can I get the uid of my users from firebase?

I am able to anonymously create a user in firebase with the below code but when I try to log the current user's 'uid' in the console it returns 'undefined'. Please advise on my below code.

  firebase.initializeApp(firebaseConfig);
  firebase.auth().signInAnonymously();

  console.log(userID);

If you want to log the UID of the user after they sign in, you have to ways to accomplish that:

firebase.auth().signInAnonymously().then((credential) => {
  console.log(credential.user.uid);
});

This will log the console when the user actively logs in.


If you instead want to respond whenever the user signs in or out, you can do:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    console.log(user.uid);
  } else {
    // No user is signed in.
  }
});

This second way works even if you restart the app, as Firebase will in that case automatically restore the user's authentication state.

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