ImranR
ImranR

Reputation: 516

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.

Upvotes: 4

Views: 24119

Answers (1)

Tameem Safi
Tameem Safi

Reputation: 728

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

Upvotes: 8

Related Questions