Calling a function after rendering a component in React.js

0

I'm making a game of the old one in React.js that uses the Minimax algorithm to produce AI's moves. This algorithm, from what I've seen, is taking between 600ms ~ 1000ms to return a move in the early stages of the game. This time would be no problem if it were not for the fact that I can not make the AI move happen after the click handler that occurs when the human player clicks on a square to make his move. Resulting in the user clicking on the square and the browser "locking" until the algorithm finishes.

Board.js

class Board extends React.Component{
    constructor(props){
      super(props);
      this.state ={
        whosTurn: this.props.playerSymbol,
        gameState: new GameState(Array(9).fill(null))
      }
    }

    handleSquareClick(index){
      let board = this.state.gameState.board;

      if(board[index] === null){
        board[index] = this.state.whosTurn;
        this.setState({
          whosTurn: Math.abs(this.state.whosTurn - 1),
          gameState: new GameState(board)
        });
      }
    }

    componentDidUpdate(prevProps, prevState){
      if(this.state.whosTurn !== this.props.playerSymbol){
        // Aqui é a função que "trava" minha execução
        let newGameState = this.state.gameState.minimax();
        this.setState({
          gameState: newGameState
        });
      }
    }

    render(){
      // Renderiza o jogo de acordo com o this.state.gameState
    }
}

I do not know much about React yet, but from what I read in the documentation, the componentDidUpdate() method comes after render() in the component life cycle, so the human player's click should not have already been rendered ?

A visual +/- example:

Time of the human player

Whenitclicks,afor-loopisfiredtosimulatethethinkingalgorithm.Noticethatthesymbolofithasnotbeenrenderedyet

Attheendoftheloop,thesymbolisfinallyrendered.Andthatwarningcomesfreeyet

Thanks for any help you can.

    
asked by anonymous 11.05.2017 / 21:51

0 answers