Panasiux2
Panasiux2

Reputation: 33

Button- fetch Frankfurt API and creating a selection with currency options from API

I have task to create a button that fetches from an API (frankfurt API). Also the same button have to create a <select> with <option> that have values and text inside same as a currency in API (options number same as the currencies in API). For example:

<select>
    <option value=”EUR”>EUR</option>
    ...
</select>

This is what I tried and where I'm stuck: HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>COCO</title>
  </head>
  <body>
    <button id="getCurrencies" onclick=Curr()>Click me</button>

    <script>
      
    </script>
  </body>
</html>

And app.js

function Curr() {
  var waluta;
  fetch("https://api.frankfurter.app/latest")
    .then((response) => {(response.json())
    .then((response) => {(waluta = response
    )})
  })
  var sel = document.createElement("select");
  let op = document.createElement("option");
  op.value = waluta.rates.euro
  document.body.appendChild(sel);
}

I appreciate any tips/help.

Upvotes: 0

Views: 283

Answers (1)

Vinny
Vinny

Reputation: 63

response.json() returns a promise thus you will have to use async. Another way to write this fetch request is

fetch("https://api.frankfurter.app/latest")
  .then(async response => {
      if (!response.ok) {
        throw await response.json();
      }
      return response.json();
  })
  .then(response => {
      waluta = response;
  })
  .catch(err => {
      console.error(err);
  })

Upvotes: 1

Related Questions