So I am kinda new to JS and I have been trying to fetch data from the API server but as you can see each currency element is assigned to a different coin value. I have also tried using for loop for the currency object but am unable to avoid this repetition.
const container=document.querySelector(".scoll_display");
const currency=container.querySelectorAll(".Exchange_rate");
async function getExchangePrice() {
const options = {
method: "GET",
headers: { "x-cg-demo-api-key": "CG-NhdhrCZRnCSqdjMyf3XUu9k4" },
};
try {
const response1= await fetch("https://api.coingecko.com/api/v3/exchange_rates", options);
const data1 = await response1.json();
currency[1].innerHTML=`(ETH) ${data1.rates.eth.value}`;
currency[2].innerHTML=`(LTC) ${data1.rates.ltc.value}`;
currency[3].innerHTML=`(BCH) ${data1.rates.bch.value}`;
currency[4].innerHTML=`(BNB) ${data1.rates.bnb.value}`;
currency[5].innerHTML=`(XLM) ${data1.rates.xlm.value}`;
currency[6].innerHTML=`(DOT) ${data1.rates.dot.value}`;
currency[7].innerHTML=`(₹) ${data1.rates.inr.value}`;
currency[8].innerHTML=`(¥) ${data1.rates.jpy.value}`;
currency[9].innerHTML=`(μBTC) ${data1.rates.bits.value}`;
currency[10].innerHTML=`(£) ${data1.rates.gbp.value}`;
} catch (error) {
console.error(error);
}
}
getExchangePrice();
3
Answers
you can use
forEach
in this case to avoid repitetion:if you want all currency data in that case no need of declaring the currencyTypes variable you can directly do it:
If you already know how many currencies you want you can add the data attribute into your element and create a function to paste the each of the value into the element like below.
If you want to parse based on the return data, it can be done as well by modifying the pasteCurrency above to be insertion into your currency exchange.
To avoid writing out individual assignments to elements’
innerHTML
, the rate property names and abbreviation need to be encoded in the code so they can be accessed progaramatically. As an example, you could try replacingwith something like