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!
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With