Reputation: 33
I have function that works when a button is clicked. The function was working well before I add the setInterval method, after I added it, it shows the error : _this2.setState is not a function
here's the function :
getWifiNetworksOnPress() {
setInterval(function timer() {
console.log("hello world");
wifi.loadWifiList(
wifiStringList => {
console.log(wifiStringList);
var wifiArray = JSON.parse(wifiStringList);
this.setState({
wifiList: wifiArray
});
},
error => {
console.log(error);
}
);
}, 3000);
}
and here's the button :
<Button onPress={this.getWifiNetworksOnPress.bind(this)}>
get location
</Button>
all the answers I found for this problem was adding .bind(this) to the onPress, but it didn't work. any idea how to solve this problem ?
Upvotes: 0
Views: 155
Reputation: 392
Why don't you use a fat-arrow function inside the setInterval function? This should work:
getWifiNetworksOnPress = () => {
setInterval(() => {
console.log("hello world");
wifi.loadWifiList(wifiStringList => {
console.log(wifiStringList);
var wifiArray = JSON.parse(wifiStringList);
this.setState({
wifiList: wifiArray
});
}, error => {
console.log(error);
});
}, 3000);
}
And
<Button onPress={this.getWifiNetworksOnPress}>
Search Networks
</Button>
Upvotes: 1
Reputation: 2859
Try adding a reference to the class using a const _this
like the following code:
getWifiNetworksOnPress() {
const this_ = this;
setInterval(function timer() {
console.log("hello world");
wifi.loadWifiList(
wifiStringList => {
console.log(wifiStringList);
var wifiArray = JSON.parse(wifiStringList);
this_.setState({
wifiList: wifiArray
});
},
error => {
console.log(error);
}
);
}, 3000);
}
Upvotes: 0