0

I have a dropdown for search via location

constructor() {
    super();
    this.state = {
     
      formData:{ }
    };

  
    this.handleSelect = this.handleSelect.bind(this);
  }

 <div class="form-group emp-searc-location ">
            <select id="emp_location"  onChange={this.handleSelect} name="emp_location" value={this.state.formData.emp_location} class="form-control">
              <option value="">Select Location name</option>
              {this.state.emplocation.map(({ branch_location, id }, index) => (
                <option value={branch_location}>{branch_location}</option>
              ))}
            </select>
          </div>

And my function

handleSelect=async(e)=>{
   
    
    this.setState({
      formData: {
        ...this.state.formData,
        [e.target.name]: e.target.value,
      },
    });
    
    console.log(this.state.formData);
             
  }

And formData seems empty.but when i console console.log(e.target.value) i got correct value.but when i console console.log(this.state.formData); i got empty value.any help would be highly appreciated.

Shanu k k
  • 1,235
  • 2
  • 18
  • 43

2 Answers2

0

As stated in the docs, setState has an additional callback parameter: React - setState()

You can utilize the callback parameter and check the updated state there.

See also: how-to-access-updated-state-value-in-same-function-that-used-to-set-state-value

Also, may I know if the async keyword is necessary?

heyitsmarcucu
  • 612
  • 5
  • 9
0

In your case, The value will be properly assigned to state. But If you put console.log(this.state.formData); immediately after setState. The value will not be replicated. For this, You can put console.log inside componentDidUpdate() like,

componentDidUpdate() {
   console.log(this.state.formData);
}

You can check the value using the componentDidUpdate().

Sujith Sandeep
  • 1,185
  • 6
  • 20