简体   繁体   中英

Passing selected value of Dropdown into API in react

Hi I need to populate list in dropdown when the page gets loaded so I put the same in componentDidMount() .

 componentDidMount() {
    axios.get(`http://localhost:8080/country_code`).then((res) => {
      const countryData = res.data;
      this.setState({ countryData });
    });
  }

This data needs to be part of dropdownlist.

      <select id="dropdown">
        {this.state.countryData.map((countryData) => (
          <option key={countryData} value={countryData}>
            {countryData}
          </option>
        ))}
      </select>

list is getting displayed like below.

在此处输入图像描述

Myrequirement is if user select any value in dropdown list that value should be passed in API as parameter to backend .

what changes I need to do in Select or Option . I know how to write call API in reactjs using axios .that I will manage. My updated code is below.

<select id="dropdown" onChange={this.downLoadFile(e)}>
                {this.state.countryData.map((countryData) => (
                  <option key={countryData} value={countryData}>
                    {countryData}
                  </option>
                ))}
</select>



downLoadFile(e) {
    this.setState({ selectValue: e.target.value });
    alert(selectValue);
  }


this.state = {
      countryData: [],
      selectValue: '',
    };
    this.handleChange = this.handleChange.bind(this);
    this.downLoadFile = this.downLoadFile.bind(this);
  }

Its not working. what wrong I am doing?

You should pass function to onChange event. Like:

<select id="dropdown" onChange={(e) => {this.downLoadFile(e)}}>

or

<select id="dropdown" onChange={this.downLoadFile}>

The way you do is just pass the return value of this.downLoadFile

You should fetch API after the update of the selected state.

downLoadFile(e) {
    this.setState({ selectValue: e.target.value }, () => {
      fetchSomeApi(this.state.selectValue).then((res) => {
         updateSomewhere(res);
      }).catch((error) => console.error(error));
    });
    alert(selectValue);
}

this.setState has second parameter as callback. So you could use that for after state update event.

Also, you can update the function call.

onChange={this.downloadFile)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM