Home > OS >  Passing selected value of Dropdown into API in react
Passing selected value of Dropdown into API in react

Time:01-18

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.

enter image description here

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?

Edit1:-

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

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

it is giving below error. enter image description here

in constrtor I have below code.

this.state = {
      selectValue: ''
    };

CodePudding user response:

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

CodePudding user response:

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)
  •  Tags:  
  • Related