Colin Riddell
Colin Riddell

Reputation: 427

Use 'this' in Firebase promise with React Native

I am having trouble using this inside a Firebase.promise .then( callback. Here's what I have:

firebase.auth().signInWithEmailAndPassword(this.state.username,
         this.state.password).then(function (result) {
           console.log("AUTH OK " + result.provider + " " + result.uid);
           this.props.navigator.push('main_page'); // Can't do this.. or anything using ''this'

        }, (error) => {  // es6 syntax fat arrow syntax to ensure 'this' is in scope
        // Handle Errors here.
        var errorMessage = error.message;
        this.setState({errorMessage: errorMessage});

      }
    );

I know about the ES 6 fat arrow syntax, but can't use the same for the then, for some reason.

It would seem like something that someone else has solved, but can't find anything about it.

Upvotes: 0

Views: 318

Answers (2)

Mathew Berg
Mathew Berg

Reputation: 28750

Javascripts this only refers to the current scope of the function. If you change your code like so:

var scope = this;

firebase.auth().signInWithEmailAndPassword(scope.state.username, scope.state.password).then(function (result) {
    console.log("AUTH OK " + result.provider + " " + result.uid);
    scope.props.navigator.push('main_page'); // Can't do this.. or anything using ''this'
}, (error) => { // es6 syntax fat arrow syntax to ensure 'this' is in scope
    // Handle Errors here.
    var errorMessage = error.message;
    scope.setState({
        errorMessage : errorMessage
    });

});

It should eliminate the problem.

Upvotes: 3

trincot
trincot

Reputation: 350079

You can also solve this with bind, like so:

  .then(function() { ... }.bind(this), 

Upvotes: 3

Related Questions