Search code examples
javascriptcoingecko

Stuck with JSON API Call in Javascript


I am trying to build a Calculator where you can Pick different Cryptocurrencies and build a Portfolio for Testing and Tracking. I choose Coingecko API v3 for this and use Fetch to do the API Calls. https://www.coingecko.com/en/api

The API Calls are working and I get JSON Data from the Server. I built a Function that is delivering the Top 100 Coins, putting them into a Datalist-Tag for Choosing from an Input:

function fetch_coinlist(url) {
  fetch(url)
    .then(function(response) {
      if (response.status !== 200) {
        alert("Can Not get Price Api! Status: " + response.status);
        return;
      }

      response.json().then(function(data) {
        document.getElementById("coinlist").innerHTML = "";

        for (i = 0; i <= 99; i++) {
          const toplist = document.createElement("option");

          toplist.id = data[i].symbol;

          toplist.innerHTML =
            data[i].symbol.toUpperCase() + " - " + data[i].name;

          document.getElementById("coinlisting").appendChild(toplist);

          //console.log(data[i].id);
          //console.log(data[i].name);
          //console.log(data[i].symbol);
          //console.log(data[i].image);
          //console.log(data[i].current_price);
        }
      });
    })
    .catch(function(err) {
      alert("Can Not get Price Api! Status: " + err);
    });
}
<input list="coinlisting" id="coinlist" name="coinlist" class="curser-choose" />
<datalist id="coinlisting" placeholder="Choose Coin"></datalist>

This is working, I am using a For loop to go through the response. I try to Display the Price for a Coin if the User picked one Option from this Datalist and for further functionality I think it would be best that I could call an object like data.coinname.current_price so I can build a Function where i could pass a string to it and get the price for that coin.

However, right now I would have to use data[0].current_price for the current Price of the first item in the list. The items on the called List can Change over time, so I can not make a static assignment, I think I could do this each time I call the API but it would not benefit my target to have a function that I can feed with a name as a string to do the Price Call.

It is possible to get the Price in the same call as the list but I can not figure out how I would be able to do what I have in mind with that. On the site for the API are different calls listed, one of the first is the /coins/list call and it says "Use this to obtain all the coins’ id in order to make API calls" and gives a JSON object for each available coin like:

{
  "id": "1inch",
  "symbol": "1inch",
  "name": "1inch"
} 

Do I need to do this call first in order to achieve what I have in mind? But I'm unsure how that would help me get the solution I am looking for... I am struggling to find a solution for this and feel stuck, I feel like I don't understand it properly and it should be not as hard as I think it is right now :D If you have an idea of how to accomplish this please let me know!


Solution

  • You could do something like this. I kept the html simple.

    • fetch_coinlist: fetches a coin list. After fetching the coins list it converts the result to an object instead of a list. Each coin can be accessed using coins["<coin id>"].
    • show_coinlist does the visualisation
    • addEventListener catches when you select an item.

    const gecko = "https://api.coingecko.com/api/v3/";
    var coins = {};
    
    // selector actions
    const selector = document.querySelector('#coinlisting');
    const info = document.querySelector('#info');
    selector.addEventListener('change', event => {
      info.innerHTML = "Selected item: " + selector.value + " : " + coins[selector.value].name;
    });
    
    function fetch_coinlist() {
      fetch(gecko + "coins/list")
        .then(function(response) {
          if (response.status !== 200) {
            alert("Can Not get List Api! Status: " + response.status);
            return;
          }
    
          response.json().then(function(data) {
            coins = {};
            for (let i = 0, l = data.length; i < l; i++) {
              let {id, ...info} = data[i];
              coins[id] = info;
            }
            show_coinlist();
          });
        })
        .catch(function(err) {
          alert("Can Not get Price Api! Status: " + err);
        });
    }
    function show_coinlist(){
      for (let id in coins) {
        let item = coins[id];
        const toplist = document.createElement("option");
      
        toplist.value = id;
        toplist.innerHTML = item.symbol.toUpperCase() + " - " + item.name;
        document.getElementById("coinlisting").appendChild(toplist);
      }
    }
    
    fetch_coinlist();
        <select id="coinlisting" placeholder="Choose Coin"></select>
        <div id="info"></div>