skip to Main Content

I’m trying to fetch the prices from coingecko API it’s returning object json response how can I get that response value and assign it to const rate directly to my calculation here the below code I’m try to achieve

fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${give}&vs_currencies=${get}`)
  .then(res => res.json())
  .then((data) => {
    console.log(data.responseText)
    const rate = data.responseText;
    rateE1.innerText = `1 ${give} = ${rate} ${get}`

    get_qty_enter.value = (give_qty_enter.value * rate).toFixed(5);
  })
  .catch(err => console.error(err)); 

2

Answers


  1. What error are you getting?

    You can process the data according to the field names in the incoming reply;

    //For example
    var rate = data.responseText;
    console.log(rate.currency, rate.amount);
    
    Login or Signup to reply.
  2. You should cultivate reading the documentation while you are exploring the new tech.

    here i wrote an example for doge to usd.

    HTML

    Amount Of Coins <br>
        <input type="text" id="give_qty_enter" placeholder="give" /><br><br><br>
    
        Total USD for Coins <br>
        <input type="text" id="get_qty_enter" placeholder="get" />
    
        <button id="rateBtn">Change</button>
    
        <h1 id="rateE1"></h1>
    

    JS

        let give = "1doge";
        let get = "usd";
        let rateE1 = document.getElementById("rateE1");
        let give_qty_enter = document.getElementById("give_qty_enter");
        let get_qty_enter = document.getElementById("get_qty_enter");
        let rateBtn = document.getElementById("rateBtn");
    
        rateBtn.addEventListener("click", () => {
            fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${give}&vs_currencies=${get}`)
                .then(res => res.json())
                .then((data) => {
                    const rate = data["1doge"].usd;
                    rateE1.innerText = `1 ${give.split("1")[1]} = ${rate} ${get}`
    
                    get_qty_enter.value = (give_qty_enter.value * rate).toFixed(5);
                })
                .catch(err => console.error(err));
        });
    

    Read these two sections carefully on this link.
    https://www.coingecko.com/en/api/documentation

    /simple/price
    /simple/supported_vs_currencies
    /coins/list

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search