Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing 'this' to Axios promise 'then'?

I have a redux-form with password field, trying to update the password word field with random number in this simple example. How to bind the 'this' to Axios catch function?

axios.get('https://www.random.org/integers/?num=1&min=1&max=20&col=1&base=10&format=plain&rnd=new').then(function(result) {
  this.props.change('password', result.data);
})
.then(function(response) {
//
})
.catch(function(error) {
  this.props.change('password', '999');
});

I know the above logic works fine because if I use an ES5 var this1 = this; and use this1 it works fine.

Regards!

like image 505
Pat Avatar asked Apr 13 '17 16:04

Pat


1 Answers

Either you can use the method you've just described, i.e.

var $this = this
var func = function() {
  $this.props.doSomething()
}

Or then you can bind the function to be executed with the right this context. In vanilla JS you can do it by using bind:

var func = function() {
  this.props.doSomething()
}
// now this inside func will always be whatever it was here
func = func.bind(this)

In es6 binding this to anonymous functions has been simplified with arrow functions:

const func = () => {
  // this will be always whatever it was where this func was defined
  this.props.doSomething()
}

Hope this helps!

like image 188
jakee Avatar answered Sep 28 '22 15:09

jakee