Austris
Austris

Reputation: 61

Can't properly update React state variables

I am working om my first React app (dice roll app). I am having troble when I call function to rol the dice, so randomly give my necesary random number for each dice.

Here is my constructor inside App class and two function I want to be executed when button is pressed. When I press the button function rollTheDice() is executed and giver random numbers and also (kind of) updates state with this.setState({diceNumber: copyDiceNumber}); and then when function diceSum() is run it sums up old state dates. For example in first "dice roll" function sum() will give number 2.

constructor() {
        super();
        this.state = {
            diceNumber: [1,1],
            total: 0,
        }
    }

    rollTheDice = () => {
        // console.log(this.state.diceNumber);

        console.log("Before roling" + this.state.diceNumber)

        let copyDiceNumber = this.state.diceNumber.slice();

        copyDiceNumber.map( (e,i) => {

            // console.log(e);

            copyDiceNumber[i] = Math.floor(Math.random() * (6 - 1) + 1)
        });

        this.setState({diceNumber: copyDiceNumber});

        this.diceSum();

        console.log("After roling" + this.state.diceNumber)

        // console.log(this.state.diceNumber);

    };

    diceSum = () => {
        let sum = 0;

        for (let i of this.state.diceNumber){
            sum = sum + i;
            console.log(sum);
        }
        this.setState({total: sum})
    };

I red that it could be because on how React renders state, in article link it says that state is updated after function is completed, but how I can call diceSum() function only after rollTheDice() function is finished?

Upvotes: 0

Views: 60

Answers (1)

Prakash Sharma
Prakash Sharma

Reputation: 16472

setState takes a second argument, a function, which is called only after the state has been set. So you can use the same here like this

   ... 
   this.setState({diceNumber: copyDiceNumber}, this.diceSum);
   ...

   or

   ... 
   this.setState({diceNumber: copyDiceNumber}, () => this.diceSum());
   ...

Upvotes: 1

Related Questions