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 = => o.label);
    // this.setState({ customer });

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

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

    // 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);'https://localhost:44303/api/observation/GetCustomerName?' + '&code=' + code).then(response => {
      //console.log('Value=' +;
      console.log('Response=' +; => {
        var obj = new Object();

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

        //this.setState({ locations: });
      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


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.