user13456401
user13456401

Reputation: 479

How to update state in ReactJS and use the values at the same time

I have some reactjs state values as below:

constructor(props) {
    super(props);
    this.state = {
      // demo button click
      age: "",
      dailyRate: "",
    };

And I am updating these two values on a button click as below and set those values to a javascript object as the next step as below:

 onDemoButtonClick() {
    this.setState({
      age: "39",
      dailyRate: "903",
    });

    // and setting those newly updated state values to a js object
    var dataframeObject = {};
    dataframeObject["Age"] = this.state.age;
    dataframeObject["DailyRate"] = this.state.dailyRate;

   // and try to print the values
   console.log(dataframeObject["Age"]) // this doesn't prin the new value
  }

As above I try to print the value to verify it if has really being updated, but no, it is not. I guess this is because the setState function is asynchronous? And if so, how can I do work this out? What is the solution?

Upvotes: 1

Views: 160

Answers (2)

Michael Eyitayo
Michael Eyitayo

Reputation: 11

That's how react works. According to the docs, there's no guarantee that the setstate will be fired synchronously.

So here's what you should do,

Assign the new JavaScript object to a variable. Then use the variable in the setState method.

Then access the values from the object

Upvotes: 0

Rinkesh Golwala
Rinkesh Golwala

Reputation: 1049

You can use setState's callback method.

 onDemoButtonClick() {
    var dataframeObject = {};
    this.setState({
      age: "39",
      dailyRate: "903",
    }, () => {
      dataframeObject["Age"] = this.state.age;
      dataframeObject["DailyRate"] = this.state.dailyRate;
      console.log(dataframeObject["Age"]);
    });
  }

Upvotes: 1

Related Questions