React push random number into array not working

React push random number into array not working
0

#1
  shuffle() {
    for(var i = 0; i < 3; i++) {
      this.shuffleCard();
    }
}

  shuffleCard() {
    const rand = array[Math.floor(array.length * Math.random())]
    if(this.state.computer.length < 2) {
      console.log(rand);
      this.setState({
        computer: [...this.state.computer, rand]
      }, () => console.log(this.state.computer));
    } else {
      this.setState({
        player: [...this.state.player, rand]
      }, () => console.log(this.state.computer));
    }    
    document.getElementById('shuffleButton').setAttribute('disabled', '');
  }

In this code it will only push the lastest generated number and push it to this.state.computer. Why it wouldn’t push the first two numbers? And more importantly what should I do to solve this problem.


#2

I have a followup question. In the else code block, did you mean to write:

    } else {
      this.setState({
        player: [...this.state.player, rand]
      }, () => console.log(this.state.player));
    }  

instead of what you wrote:

    } else {
      this.setState({
        player: [...this.state.player, rand]
      }, () => console.log(this.state.computer));
    }  

Either way, I believe the problem you are experience is do to setState being asynchronous. This means when ever you update a state property and immediately try to view the state, it may not be changed yet. The setState method decides on it’s own when to update the actual state. Sometimes it will batch many requests for state update and update them all at the same time. Even though it is taught in Free Code Camp you can update state like below:

// assume this.state.count = 1
this.setState({
  count: this.state.count + 1
}

This does not guarantee state will be updated immediately before setState is called again. In your case, you are iterating throw a for loop in the shuffle method, so the loop probably completes before the first setState has completed. What ends up happening, is that only the last setState sticks. Read about the updater in the React documentation which explains what I have written below.

Try using a function to update state like below:

  shuffleCard() {
    const rand = array[Math.floor(array.length * Math.random())];
    if (this.state.computer.length < 2) {
      this.setState(prevState => ({
          computer: [...prevState.computer, rand]
        }), () => console.log(this.state.computer)
      );
    }
    else {
      this.setState(prevState => ({
          player: [...prevState.player, rand]
        }), () => console.log(this.state.player)
      );
    }
  }