Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda