'Display value of a response from an api at JavaScript [duplicate]

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


Solution 1:[1]

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'.

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alexanderdavide
Solution 2 Kishan Vaishnani