I`m learning React and I do not understand – why in first render React generate correctly value playerSymbol, but when It changes it is not re-render even when gameBoard changes. Code:
import { useState } from "react";
const initialGameBoard = [
[null, null, null],
[null, null, null],
[null, null, null],
];
export default function GameBoard() {
const [gameBoard, setGameBoard] = useState(initialGameBoard);
function handleSelectedSqare(rowIndex, colIndex) {
console.log("aaaa");
setGameBoard((prevGameBoard) => {
const updatedBoard = [
...prevGameBoard.map((innerArray) => [...innerArray]),
];
console.log(updatedBoard);
updatedBoard[rowIndex][colIndex] = "X";
return updatedBoard;
});
}
return (
<ol id="game-board">
{initialGameBoard.map((row, rowIndex) => (
<li key={rowIndex}>
<ol>
{row.map((playerSymbol, colIndex) => (
<li key={colIndex}>
<button onClick={() => handleSelectedSqare(rowIndex, colIndex)}>
{playerSymbol}
</button>
</li>
))}
</ol>
</li>
))}
</ol>
);
}
Any idea guys?
2
Answers
was called instead call gameBoard
You are not changing the state of gameBoard. You need to pass in the new board to setGameBoard().