Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
set state and access updated state in a same function

How can we access updated states in the same function?

state = {
    a: 1,
    b: 2,
  };

  updateState = () => {
    const { a, b } = this.state;

    console.log("previous a", a);
    console.log("previous b", b);

    this.setState({ a: b, b: 3 });

    console.log("New a", a); <-- getting previous value here
    console.log("New b", b); <-- getting previous value here

  };

is it possible to get a new value in the same function?

async and await are not working here. function method where we apply function as a 2nd parameter to the setstate is not working for the whole application.

please do not flag this question.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You could use this.setState's callback in this way:

state = {
    a: 1,
    b: 2,
  };

  updateState = () => {
    const { a, b } = this.state;

    console.log("previous a", a);
    console.log("previous b", b);

    this.setState({ a: b, b: 3 }, () => {
       console.log("New a", this.state.a);
       console.log("New b", this.state.b);
    });
  };

EDIT to print new state values you could use also componentDidUpdate in this way:

componentDidUpdate(prevProps, prevState) {
  if (prevState.a !== this.state.a) {
    console.log("New a", this.state.a);
  }
  if (prevState.b !== this.state.b) {
    console.log("New b", this.state.b);
  }
}
about 4 years ago · Juan Pablo Isaza Report

0

you are using a local constant variable whose value is not changed. so if you want to use updated value use this.state.a and this.state.b for respective value.

  state = {
    a: 1,
    b: 2,
  };

  updateState = () => {
    const { a, b } = this.state;

    console.log("previous a", a);
    console.log("previous b", b);

    this.setState({ a: b, b: 3 });

    console.log("New a", a); <-- getting previous value here  // problem is here
    console.log("New b", b); <-- getting previous value here  // problem is here
    //replace above code with below code 
    console.log("New a", this.state.a);  //replace with this code.
    console.log("New b", this.state.b); //replace with this code

  };
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!