Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate select dropdown elements with data from API - ReactJS

I'm fairly new to React. I'm fetching data from an API, and I can see the data when I check console log. However I can't figure out how I can use map() to create a new array which the option elements can then use to display the currency codes.

Currently it populates the dropdown, but the option elements are all empty and results show up as NaN.

Below is a sample of my code where I am fetching the data.

state = {
    currencies: [],
    base: "USD", //default value
    amount: "",
    convertTo: "EUR",
    result: ""
  };

componentDidMount() {
    fetch("https://api.exchangeratesapi.io/latest")
      .then(response => {
        return response.json();
      })
      .then(data => {
        let currenciesFromApi = Object.keys(data.rates);
        console.log(currenciesFromApi);
        this.setState({
          currencies: currenciesFromApi
        });
      })
      .catch(error => {
        console.log(error);
      });
  }

Expected Results: Dropdown to be populated with currency codes from API (eg GBP, EUR, USD) and value to display rates and not NaN.

Actual Results: Dropdowns are empty and selecting any of these also return Nan.

like image 754
ImranR Avatar asked Oct 21 '25 15:10

ImranR


1 Answers

I checked the source code and it seem the array of currencies contains just string values. So when you map through them to render the options, just use the variable directly as a string.

{this.state.currencies.map(currency => (
  <option key={currency} value={currency}>
    {currency}
  </option>
))}

See: https://codesandbox.io/s/hu8cb

like image 118
Tameem Safi Avatar answered Oct 23 '25 04:10

Tameem Safi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!