4

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.

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

I see, silly mistake but good to know next time. Is there anything I could have done better where I have fetched the data?
You can maybe separate the fetch call into a function inside another file so it can be reused. Also maybe you can look into react hooks instead of using the class component. See: robinwieruch.de/react-hooks-fetch-data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.