Skip to content

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

Answer

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.