Search code examples
reactjsrerender

Nested array not rerendering in React even using spread operator


I am making a sudoku game using React, and when I am clicking on a cell to update it, the component does not rerender. The sudoku board is an array of arrays. I am using the spread operator to create a copy of the array, but that is not doing anything. If I console.log to see, the array of arrays is updated properly.

export default function NineSquare() {
  const cube = Array(9).fill('X');
  const blankSquares = Array(9).fill(cube);

  const [board, setBoard] = useState(blankSquares);
  const [currentSquare, setCurrentSquare] = useState(null);
  const [chosen, setChosen] = useState();

  function setCell(val) {
    if (chosen) {
      let outer = Number(chosen.split('-')[0].slice(1));
      let inner = Number(chosen.split('-')[1]);
      let newBoard = [...board];
      newBoard[outer] = [...newBoard[outer]];
      newBoard[outer][inner] = val;
      setBoard(newBoard);
    }
  }


  const bigBoard = blankSquares.map((item, index1) => {
    const squareId = shortid.generate();
    const sudokuRow = item.map((cell, index2) => {
      const cellId = shortid.generate();
      return <td className={`_${index1}-${index2}`} key={`${index1}-${index2}`} onClick={(e) => setChosen(e.target.className)}>{cell}</td>
    })
    return <tbody className={`square${index1}`} key={index1}><tr key={index1}>{sudokuRow}</tr></tbody>
  })


  return (
    <>
      <table className="board">{bigBoard}</table>
      <Numbers setCell={setCell}/>
    </>
  )
}

I also tried creating a new array using JSON.parse(JSON.stringify(board)) but nothing happened.


Solution

  • You're using blankSquares to map the render items, which is the initial array.

    const bigBoard = blankSquares.map((item, index1) => {
      // return render items
    })
    

    Try to use board instead so that the latest content will be rendered.

    const bigBoard = board.map((item, index1) => {
      // return render items
    })