-2

I'm trying to create a calculator in JavaScript. In this calculator I have a button to convert the number inputed by user to dollars. I have an api with a key but somehow I can't make it to display the result on the calculator.

case 'convert':
            let eur = parseFloat(num)
            console.log(eur)
            const url = 'https://v6.exchangerate-api.com/v6/my-api-key/pair/EUR/USD/' + eur
            fetch(url)
                .then(response => response.json())
            let converted = JSON.parse(response.json())
            display.value = converted
            num = 0
            break
Dario Santos
  • 74
  • 1
  • 8

2 Answers2

0

Method 1:

You can do asyn call your function with await the APIs request

let response = await fetch(url);
let converted = JSON.parse(response.json())
display.value = converted

Method 2:

Move your parsing code inside the APIs response, and get the converted values and set it to display field

Kishan Vaishnani
  • 234
  • 1
  • 12
0

The first problem you have is that you're not processing the API result properly.

response only exists inside your Promise callback. In the initialization of your converted variable, response is not defined. Following should at least successfully give you the data from the API which you can then use for display. Besides, calling .json() on a fetch Response already converts the HTTP body to JSON so there is no need to parse it again with JSON.parse().

fetch('https://v6.exchangerate-api.com/v6/my-api-key/pair/EUR/USD/4')
    .then(response => response.json())
    .then((responseData) => {
        console.log(responseData);
        display.value = responseData;
    });

As you haven't provided information on what is behind display.value, you may encounter further issues. Also, I hope you have recognized that an API key for this API is required and your URL just says 'my-api-key'.

alexanderdavide
  • 1,487
  • 3
  • 14
  • 22
  • I replaced my real api with "my-api-key" just to not shar the real key. display.value it's used to display the result on the calculator. – Dario Santos Apr 25 '22 at 09:36