Reputation: 201
<select value={this.state.selectedValue} onChange={this.handleChange} size={5}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
changecountry(value){
//some code here
}
handlechange = (event) => {
let value = event.target.value
setTimeout(function (){
this.changecountry(value)
}
}, 300);
I am trying to call changecountry inside setTimeout function. getting this.changecountry is not a function error what is wrong with this code?
Upvotes: 0
Views: 1299
Reputation: 1568
Update your setTimeout to
setTimeout(() => this.changecountry(value) , 300);
this
context will change inside function(){}
in setTimeout. Arrow Function
is lexical scoped, will take reference from where it was created.
You can also bind the setTimeout callback,since handleChange
is already an arrow function.
setTimeout(
function () {
this.changecountry(value);
}.bind(this),
300
);
Upvotes: 1
Reputation: 1130
I think it's usefull to explain why you're getting this error. It is because the wrong context is passed to the handleChange
function. There are several ways to fix this error.
First option: here you pass an anonymous function thus keeping the context of your class. Else the context of the event handler function is passed.
<select value={this.state.selectedValue} onChange={(event) => this.handleChange(event)} size={5}>
Or you could bind the handleChange
function:
// Change your original function name to "_handleChange" for better code visibility
_handlechange(event) {
// ...
}
// Pass the current this context to your new handleChange function
handleChange = this._handleChange.bind(this);
Upvotes: 0