0

so in my react code I have this:

  componentDidMount = () => {
    firebase.auth().getRedirectResult().then(function(result) {
        if (result.credential) {
          var token = result.credential.accessToken;
        }
        var ruser = result.user;
        console.log(ruser.displayName, 'lol'); //THIS LOGS CORRECTLY
      }).catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;
        var email = error.email;
        var credential = error.credential;
      }).then(function(result){
        this.setState({user: ruser});
        console.log(result, 'rslt'); //THIS LOGS UNDEFINED 
      });

  }

I basically want to set the state of the user who is logged in. however, I get undefined when I pass this down, what have I done wrong with promises? i want to just pass down the result and make it available outside the scope of the function...

AL.
  • 36,815
  • 10
  • 142
  • 281
The worm
  • 5,580
  • 14
  • 36
  • 49

1 Answers1

0

Declarations from within a promise are meaningless unless you return what you declared - you have to return result if you want to pass it down:

componentDidMount = () => {
  firebase.auth().getRedirectResult().then(function(result) {
      if (result.credential) {
        var token = result.credential.accessToken;
      }

      console.log(result.user.displayName, 'displayName');

      return result; // this will be passed down
    }).catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;
      var email = error.email;
      var credential = error.credential;
    }).then(result => {
      this.setState({user: result.user});

      console.log(result.user, 'user'); 
    });
}

Also - as nils mentioned you have to use arrow function in the last .then to use parent's context and it's setState.

biphobe
  • 4,525
  • 3
  • 35
  • 46
  • Don't forget to also `return` something meaningful from the `catch` callback - or move that to the end – Bergi Mar 15 '17 at 05:24