Search code examples
javascriptreactjsfor-loopbreak

React for loop issue


I beg your pardon, I tried to use "break" statement in for loop while writing React JS, but eventually the state hasn't been updated. Did I use this statement correctly or the syntax shall be modified?

for (let i = j; i < 42; i += 6) {
    /* if(i > 35 && !board[i]){
      board[i] = this.state.xIsNext ? 'X' : 'O';
    }
    else if (board[i]) {
      while (board[i-6 * k]) {
        k++;
      }
      board[i-6 * k] = this.state.xIsNext ? 'X' : 'O';
    } */
    if (i > 35 && !board[i]) {
        board[i] = this.state.xIsNext ? 'X' : 'O';
    } else if (board[i]) {
        board[i - 6] = this.state.xIsNext ? 'X' : 'O';
        break;
    }
}

Solution

  • sorry I cannot comment, you don't seem to be updating your state, that's why it doesn't get updated. You should either use hooks setBoard for example or if you have a class component (which seems to be your case) use this.state={....} to update your state. If you share more code I might be able to give you a better answer