Chris Atkeson
Chris Atkeson

Reputation: 71

React SetState Twice in Same Function

Assume you have a Chess class with a make move function like the one below. Right after the user makes a move we let the chess engine reply with its own move. All is well, except for the fact that the browser does not repaint until the second setState is called which means the user move and the engine move show up at the same time with a 3 second delay. This is obviously not good for the user since the piece they move disappears and then two moves appear immediately. My question is how would you structure these functions or class so that the browser can render the users move before it computes the engine move. Thanks.

class Chess extends Component {
  constructor(props) {
    super(props);
    this.state = {
      chess_board: Array(64).set(null);
  }
}
//User makes a move
makemove_on_dragend(move) {
  const chess_board = this.state.chess_board;
  if (move is legal) {
    let new_board = chess_board.make_move(move);
    this.setState({chess_board: new_board})
  }
  this.chess_engine_move();
}
// Chess engine makes a move
chess_engine_move() {
    const chess_board = this.state.chess_board;
    let search_time = 3 seconds;
    let move = alphabeta(search_time, chess_board);
    let new_board = chess_board.make_move(move);
    this.setState({chess_board: new_board});
}

Upvotes: 2

Views: 1444

Answers (1)

Root
Root

Reputation: 2361

First,setState is an asynchronous function,so you can't decide when the first setState runs.So I recommend to force it run synchronous.

this.setState({chess_board: new_board},()=> {console.log(this.state.chess_board)})

Second,use a setTimeout to analogy the delay

setTimeout(this.chess_engine_move(),3000);// delay 3s

Upvotes: 3

Related Questions