I have a task to get and display in html a particular data from API result (console.log). For now on, I only have a javascript that gets exchange rates with currency conversion. From fetched data I only need currency rate.
var myHeaders = new Headers();
myHeaders.append("apikey", "r4T22n3O14QL7FoG6FzY7FuUHTNXiKAy");
var requestOptions = {
method: 'GET',
redirect: 'follow',
headers: myHeaders
};
//var rslt = console.log(result);
fetch("https://api.apilayer.com/currency_data/convert?to=RUB&from=EUR&amount=1", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Here is the result I get in console.log and my problem is that I cannot display : 1. anything from that log to HTML and 2. particular data (rates) from that log.
this is the console log I am getting:
{
"success": true,
"query": {
"from": "EUR",
"to": "RUB",
"amount": 1
},
"info": {
"timestamp": 1658378463,
"quote": 56.217115
},
"result": 56.217115
}
I need to get a rates/"quote" as a variable in order to use it elsewhere.
Thank you in advance.
Use response.json() and then extract the properties that you want into variables.
fetch("https://api.apilayer.com/currency_data/convert?to=RUB&from=EUR&amount=1", requestOptions)
.then(response => response.json())
.then(json => {
let quote = json.info.quote;
document.getElementById("quote").innerText = quote;
})
.catch(error => console.log('error', error));
Replace "quote" with the actual ID of the element where you want to show the quote.
To display value using HTML, you need to use Template literals concept in javascript. You can set elements with a unique ID in HTML. Using HTML DOM Element innerHTML Property and Template Literals you can achieve.
Particular data (rates) from that log:
let rate = result.result;
As I mentioned above you will get the rate result.
Assuming you have something like
<div id="quote"></div>
in your html,
I would do something like this:
.then(response => response.json())
.then(data => { document.getElementById('quote').innerHTML = data.info.quote})
.catch(error => console.log('error', error));
see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch