I am trying to reset an array using the setState method in React. In the constructor I have set tile_arrays to null initially.
The first console.log() produces the desired array of N Tile objects after the nested for loops finish. When setState is called and the subsuquent console.log() after, the state is still null and was not updated.
I am not trying to append new information to the states array, but replace it entirely.
createTileArray(){
let new_array= [];
let size = this.state.size;
for(let row = 0; row < size; row++){
for(let column = 0; column < size; column++){
if(row === 0 || row === 1){
//Player 1
new_array.push(new Tile(column, row, true, 1))
}
else if(row === size - 1 || row === size - 2){
//Player 2
new_array.push(new Tile(column, row, true, 2))
}
else{
//Empty Tile
new_array.push(new Tile(column, row, false, 0))
}
}
}
console.log("Tile to be set into the state", new_array)
this.setState({
tile_arrays:new_array
},
() => console.log("Updated Tiles: ", this.state.tile_arrays))
}
console.logis not matching the secondconsole.log? You can edit your question and add a new section below the current information to represent your current code-state.