I'm trying to update the game data but it comes from behind. I think I should call this.setState({})
in a different sort of way, but can anybody help me doing it?
Here's the code:
handleMove(cords) {
// Return if the game is already over
if (this.state.winner) {
return
}
// This should be the copy of the this.state.history till the end
const history = this.state.history.slice();
const current = history[history.length - 1];
// Cords parameter is an array of coordinates of squares whose values are
//to be changed or passed in
const color = this.state.blackIsNext ? "black" : "white";
// Here, I create a new squares array, states of each squares
//one-by-one are added, which will be immutably pushed inside the new history
//array
const nextSquares = current.squares.map((row, y) =>
row.map((square, x) =>
// find if this [x,y] is in the cords array and replace it if it is
cords.some((cord) => cord[0] === y && cord[1] === x) ? color : square
)
);
// Create the new history element, element's state.history
//value will be this new one
const newHist = history.concat({squares: nextSquares})
this.setState({
history: newHist,
stepNumber: history.length,
});
If this code is not enough to give you a hint, then please do let me know. Thanks a lot in advance.