I have a Button. This will be clicked and get the value of a counter. This counter values are set to the state variable. After that I want to update the counter with a new number. My problem is that the state variable is not updated in time when I wanted to update the counter.
How can I wait until the state variables are updated?
Here is my code so far:
At first I click the Button:
<div><PrimaryButton text="Create Update and TS Item" onClick={()=>this.CreateAndUpdateTS()}/></div>
Then I call another function which get the values of the counter:
private CreateAndUpdateTS(){
this.getCounterValue()
console.log("NewID: "+this.state.counterOldID);
console.log("ID: "+this.state.counterID);
let TSID = this.state.counterID;
console.log("ID 2: "+TSID);
let counterAdd =1;
let counterOld = this.state.counterOldID;
let counterNew = counterOld + counterAdd;
console.log("ID"+ this.state.counterID +" CounterNew"+counterNew);
this._spDataProvider.CounterUpdate("Counter",this.state.counterID,counterNew);
}
But I always get the wrong values after I called this.counterValue()
. I need to wait until the state is updated. How can I do that?
console.log("NewID: "+this.state.counterOldID); console.log("ID: "+this.state.counterID);
useEffect
. you can pass callback function to setState. check my answer given below.