skip to Main Content

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


  1. you can use forEach in this case to avoid repitetion:

    1. declare array of currency:
    const currencyTypes=['eth','ltc','bth'....etc] ;
    
    1. forEach loop:
     currencyTypes.forEach((type, index) => {
                currency[index + 1].innerHTML = `(${type.toUpperCase()}) ${data.rates[type].value}`;
            });
    

    if you want all currency data in that case no need of declaring the currencyTypes variable you can directly do it:

    Object.keys(data.rates).forEach((type, index) => {
                currency[index + 1].innerHTML = `(${data.rates[type].unit}) ${data.rates[type].value}`;
            });```
    
    Login or Signup to reply.
  2. 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.

    let data = {
      rates : {
          eth: 4000,
          btc: 2000,
          idr: 3000,
          myr: 2000
      }
    };
    
    let pasteCurrency = (currency, value) => {
    let el =  document.querySelector('.currency[data-currency="'+ currency +'"]');
      el.innerHTML = `${currency} ${value}`;
    }
    
    for (const [key, value] of Object.entries(data.rates)) {
      pasteCurrency(key, value);
    }
    <div class="currency" data-currency="eth"></div>
    <div class="currency" data-currency="btc"></div>
    <div class="currency" data-currency="idr"></div>
    <div class="currency" data-currency="myr"></div>

    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.

    Login or Signup to reply.
  3. 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 replacing

    
      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}`;
    

    with something like

    const rates = {
      eth: "ETH",
      ltc: "LTC"
      bch: "BCH"
      bnb: "BNB",
      xlm: "XLM",
      dot: "DOT",
      inr: "₹",
      jpy: "¥",
      bits: "μBTC"
    };
    Object.entries(rates).forEach( (entry, i) => {
      const {key, value} = entry;
      currency[i+1].innerHTML = `(${value}) ${data.rates[key].value}`;
    });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search