0

I have an array state variable which I am trying to set to an array created during the componentWillMount() method

getInitialState: function() {
return {
  matrix: [],
  generation: 0,
  neighbors: [[0,1], [1,0], [-1, 0], [0, -1], [1, 1], [-1, -1], [-1, 0], [0, -1]]
};
},

componentWillMount: function() {
function Cell() {
    this.neighbors = 0;
    this.isAlive = false;
};

var matrix = [];
var dim = this.props.dim;

for (var i = 0; i < dim; i++) {
  var row = [];
  for (var j = 0; j < dim; j++) {
    row.push(new Cell());
  }
  matrix.push(row);
}

this.setState({matrix: matrix});
this.createGrid();
},

As you can see, I am populating the 'matrix' variable inside the cwm() method and setting the state 'matrix' variable equal to this new 'matrix' variable. So, the state matrix variable should be populated with a bunch of Cells after this method runs.

However, in the createGrid() method which is called from the cwm() method I attempt to access an element in the matrix like this:

var currentCell = this.state.matrix[i][j];

However, this causes an error which says: Cannot read property '0' of undefined.

I would like to know why the state variable is not being set and how I can fix it.

Cheers.

1 Answers1

0

setState is asynchronous which means the state isn't updated yet by the time you call this.createGrid();

You can call createGrid after the state has been updated by passing in the function as the callback argument

this.setState({matrix: matrix}, this.createGrid.bind(this));

Another possible solution is to pass matrix to this.createGrid(matrix) and to set the state there.

FuzzyTree
  • 32,014
  • 3
  • 54
  • 85