Home > database >  Why is data showing undefined?
Why is data showing undefined?

Time:12-31

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

CodePudding user response:

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;

CodePudding user response:

Okay, I just looked in documentation, there is one clear mistake in your code.

Example of data you get:

{
  "base": "USD",
  "results": {
    "EUR": 0.93803,
    "GBP": 0.83176,
    "CHF": 0.92473
  },
  "updated": "2022-12-30 13:52:50",
  "ms": 2
}

As you can see, there is results property where all data you need is stored, so all you just need to do is this:

fetch(`https://api.fastforex.io/fetch-multi?api_key=1234567891221&from=USD&to=EUR,GBP,CHF`)
  .then(response => response.json())
  .then(data => {
    let results = data.results
    document.getElementById("eur").innerHTML = results.EUR;
    document.getElementById("gbp").innerHTML = results.GBP;
    document.getElementById("chf").innerHTML = results.CHF;
});
  • Related