skip to Main Content

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


  1. Chosen as BEST ANSWER
      {initialGameBoard.map((row, rowIndex) => (
    

    was called instead call gameBoard


  2. You are not changing the state of gameBoard. You need to pass in the new board to setGameBoard().

    setGameBoard(updatedGameBoard)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search