0

I have a grid display based on an array of array (2D grid). Each cell / node in the grid is represented by an object. I am running the following code to update the nodes so that it changes color with interval, but it seems that after only one interval all the state gets updated at the same time.

export const updateGrid = (grid, setGrid) => {
  for (let i = 0; i < 1; i++) {
    for (let j = 0; j < 3; j++) {
      let node = grid[i][j]
      node['status'] = 'discovered'
      grid[i][j] = node
      setTimeout(() => setGrid([...grid])
      , 1000)
    }
  }
}

I have a 3 x 3 grid, the above code is supposed to change the property of a node, thus, the color of the cell every second for 3 cells. But it just waits 1 second and changes the color of all three cells at the same time.

How can I fix this?

MiniGunnR
  • 5,170
  • 6
  • 39
  • 62
  • Does this answer your question? [Calling setState in a loop only updates state 1 time](https://stackoverflow.com/questions/35248748/calling-setstate-in-a-loop-only-updates-state-1-time) – Sinan Yaman Jun 22 '21 at 13:08

0 Answers0