0

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?

4
  • Do you get correct values at these lines? console.log("NewID: "+this.state.counterOldID); console.log("ID: "+this.state.counterID); Aug 3, 2023 at 11:45
  • Also, you can pass callback function to setState as mentioned here: stackoverflow.com/questions/37401635/…. let me know if it works for you. Aug 3, 2023 at 11:57
  • No, I didn't get the correct values. useEffect is not working in my case.
    – Matthias
    Aug 3, 2023 at 12:01
  • You don't have to use the useEffect. you can pass callback function to setState. check my answer given below. Aug 3, 2023 at 12:23

1 Answer 1

0

Try something like this:

private CreateAndUpdateTS(){
    this.getCounterValue()
}

private getCounterValue(): void {
    this._spDataProvider.ReadCounterValue("Counter").then((items)=>{  
        console.log("Counter Value: "+ JSON.stringify(items))
        console.log(items[0].NewId);
        this.setState(
            {
                counterID: items[0].NewId
            },
            this.updateCounterValue // your callback function
        )
    })
}

private updateCounterValue(): void {
    console.log("ID: " + this.state.counterID);

    let counterAdd = 1;
    let counterOld = this.state.counterID;
    let counterNew = counterOld + counterAdd;

    this._spDataProvider.CounterUpdate("Counter", this.state.counterID, counterNew);
}

Reference: How can I wait for setState to finish before triggering a function in React?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.