0

I am building a game of life with React. When I set "alive" cells by clicking on them 1-2 times per second it works fine, but when I try to click faster there is an error:

"TypeError: Cannot read property 'undefined' of undefined".

Error pointing to the fourth line of functional expression:

const onClick = (e) => {
    const indexies = e.target.id.split(",");
    const x = indexies[0];
    const y = indexies[1];
    setGrid([...grid], (grid[x][y] = !grid[x][y])); //error line
  };
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Megachel
  • 1
  • 1
  • Since state updates are async, it might happen that too fast changes doesn‘t reflect the current state. This may help to throttle your state updates: https://stackoverflow.com/questions/54666401/how-to-use-throttle-or-debounce-with-react-hook – Dennis Sep 05 '20 at 21:41

1 Answers1

0

Updating the Grid State using a function is probably going to solve your issue:

setGrid((prevGridState) => "return your new state here")