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

100
Visualizações
How to store the value of a variable in state immediately when set state is async

I am new to react and am trying to store the value in state for customer my code for getting the value of the dropdown is this:

handleChangeCC = customercode => {
    this.setState({ customercode });

    // var customer = customercode.map(o => o.label);
    // this.setState({ customer });

    var customer1 = customercode.label;
    this.setState({ customer: customer1 });

    console.log(`Option selected1:`, this.state.customer);
    this.getCustomerName();

    // console.log("Rec2:" + document.getElementById("CustomerCode").innerText);
  };

I am running function this.getCustomerName() in this function, The code for that is this:

getCustomerName = () => {
    var Items = [];

    var code = this.state.customer;
    console.log('CustomerCode:' + code);
    axios.post('https://localhost:44303/api/observation/GetCustomerName?' + '&code=' + code).then(response => {
      //console.log('Value=' + response.data);
      console.log('Response=' + response.data);
      response.data.map(item => {
        var obj = new Object();

        // obj.label = desc;
        obj.label = item;

        Items.push(obj);
        //this.setState({ locations: response.data });
      });
      this.setState({ customerName: Items });

      console.log('customerName:' + this.state.customerName);
    });
  };

I am setting code= this.state.customer in the function getCustomerName which I am running just after this.setState({ customer: customer1 }); in handleChangeCC function.

However as this.setState is an async function it is not updating the state immediately as a result of which I am getting code as null and my getCustomerName function does not work

How do I get around This? Is there a way to get the variable value of one function to another function. Please help

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I would pass the customercode into your getCustomerName() method, in this instance. setState will take a moment, so it's value won't be immediately available to your method. You would have to wait for the value to be in state and then call the method. By setting its' state and passing it to your method, you don't have to wait for the state update to complete.

Also, if you're just learning React I would look into using function based components instead of the legacy class components, if you have the option.

about 4 years ago · Juan Pablo Isaza Relatório

0

Yes, there are several techniques to get the latest value

2nd argument in setState

this.setState({ customerName: Items }, () => {
    console.log('latest value', this.state.customerName);
});

The second argument that can optionally be passed to setState is a callback function that gets called immediately after the setState is completed and the components get re-rendered.

More here

async methods

  updateA = async () => {
    this.setState({
      a: "test"
    });
    await (() => {})(); // or fetch or any async operation
    console.log(this.state.a);
  };

Do note this isn't recommended approach however current version of react supports it.

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