I have a really simple React App, where you just click on the different color from the set and it re-renders to another color set. To load the game you press the button Pick color > Loads Color. I tried to create a Start Button that is just a method that calls Pick Color and Loads Color but I dont understand why it is not working properly. It seems like Loads Color runs before Pick Color finishes and that's why there is an error. If I do a setTimeout inside start for Loads Color, it will end up running correctly.
https://codepen.io/dnangels/pen/yLeVBZg
pickColorPair() {
const randomNumber = Math.floor(Math.random() * 4);
this.setState(() => ({ colorPair: this.colorSet[randomNumber] }));
console.log(this.state.colorPair);
}
loadColor() {
// console.log(this.state.colorPair);
let colorArray = [this.state.colorPair[0]];
for (let i = 1; i < this.state.size; i++) {
colorArray.push(this.state.colorPair[1]);
}
this.randomize(colorArray);
this.setState(() => ({ colors: colorArray }));
}
Does anyone have a solution for this? How can I get Loads Color to run after Pick Color. Thanks!