Search code examples
javascriptfetch

Why is data showing undefined?


Could anyone help me with this ! The rates in table is showing undefined.

Here's the code ,

I want to get rates using fastforex.io api

<!DOCTYPE html>
<html>
<head>
  <title>Currency Conversion</title>
</head>
<body>
  <h1>Currency Conversion</h1>
  <table>
    <tr>
      <th>Currency</th>
      <th>Exchange Rate</th>
    </tr>
    <tr>
      <td>EUR</td>
      <td id="eur"></td>
    </tr>
    <tr>
      <td>GBP</td>
      <td id="gbp"></td>
    </tr>
    <tr>
      <td>CHF</td>
      <td id="chf"></td>
    </tr>
  </table>
  <script>
    // Fetch the exchange rates from the API
    fetch(`https://api.fastforex.io/fetch-multi?api_key=1234567891221&from=USD&to=EUR,GBP,CHF
`)
      .then(response => response.json())
      .then(data => {
        // Update the exchange rates in the table
        document.getElementById("eur").innerHTML = data.EUR;
        document.getElementById("gbp").innerHTML = data.GBP;
        document.getElementById("chf").innerHTML = data.CHF;
      });
  </script>
</body>
</html>

The rates data showing undefined.

enter image description here


Solution

  • If you console.log data or you check the documentation, you can see that the data you really want is in the object results.

    So in your last 'then', you want to do something like that :

    document.getElementById("eur").innerHTML = data.results.EUR;
    document.getElementById("gbp").innerHTML = data.results.GBP;
    document.getElementById("chf").innerHTML = data.results.CHF;