I'm using property initializers. This is my state.
state = {
status: 'Simon Says!',
compArr: [],
color: 'red',
userArr: []
};
This is my pen.
I call the state here
game = (event) => {
let compArr = this.state.compArr;
for (let i = 0; i < compArr.length; i++) {
(function(i) {
setTimeout(function() {
switch (compArr[i]) {
case 1:
this.setState({
color: 'green'
});
break;
case 2:
this.setState({
color: 'red'
});
break;
case 3:
this.setState({
color: 'yellow'
});
break;
case 4:
this.setState({
color: 'blue'
});
break;
}
}, 1000 * i);
}(i))
}
};
I get the following error
Uncaught TypeError: this.setState is not a function
How do I fix this in ES2015+?
const colors = ['green', 'red', 'blue', 'yellow'];
and just callthis.setState({color: colors[compArr[i] - 1]})
. No wrapping functions needed. – Sulthan