Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda