React - Array size change bug

React - Array size change bug
0.0 0

#1

I am working on my game of life challenge and trying to implement a feature for the user to change the size of the board that the game is played on. The board itself is represented by a 2D array which I recreate every time the user selects a different size. I have implemented this function which runs when the user clicks a button to change the size of a square board:

createBoard(size){
  this.setState((previousState)=>{
	let {board} = previousState;
	board = [];
	for(let i = 0; i < size; i++){
	  board.push([]);
	  for(let j = 0; j < size; j++ ){
	    board[i].push(0);
          }
        }
        return {board: board}
  });
}

This works great when the user goes up in size from 20x20 to 40x40 to 80x80. The problem occurs when the user starts to go down in size from 80x80 to 40x40 etc. Its hard to describe what is happening because it is really strange. I have tried to use the setState function without the callback too and it is doing the same thing. I am now trying to do slices to remedy this, and its still happening. Any ideas? Here is my pen so you can see the issue.


#2

What is checkNeighbors() supposed to do? If you look at the browser console, it implodes because neighborCheck and checkNeighbors keeps trying to access a property.

Edit: Okay, after looking what Game of Life is supposed to do, I’m guessing it’s not supposed to be active until the game is playing.
The problem is that when you assign a setTimeout to a variable, it’ll execute it.

		this.timerID = setTimeout(()=>{
			this.neighborCheck()}, 1000
		);

This line is what was causing the trouble


#3

Ah, thank you! Ok, I left that line in while I was testing the checkNeighbors function and didn’t realize it was going to be causing issues down the line as I started testing changing the board size. Thank you so much!!!