0

I have this function:

let userDisplayName;
firebase.auth().onAuthStateChanged(function(user){
  if (user){
    userDisplayName = user;
  }
  else {
    console.log('error');
  }
  this.setState ({user: userDisplayName})
  return userDisplayName;
})
console.log(userDisplayName, 'udn');

userDisplayName is giving me the correct value however, only in the scope of the function. When I console.log I am told that the value is undefined and when I try to setState I get told I cant use that function inside there (doesn't know what this is). How can I return the variable so that it has the value I'm expecting outside the scope so that I can set state with it?

The worm
  • 5,580
  • 14
  • 36
  • 49
  • Putting the call outside of the callback means that it does not wait for anything, which you always need to do with asynchronous methods. Notice that `return userDisplayName;` does not work either in a non-promise callback – Bergi Mar 10 '17 at 15:50
  • and you need to bind `this` https://facebook.github.io/react/docs/handling-events.html – Lyubomir Mar 10 '17 at 15:52
  • @Bergi so how can I resolve the async stuff? What would the promise look like? – The worm Mar 10 '17 at 16:17
  • Afaik firebase already provides a promise-based API, try searching for that – Bergi Mar 10 '17 at 18:48

0 Answers0