I am trying to figure out how I would just request the top 5 crypto coins via api request to coinranker as I want them to fit on a section on my html page. As of now I am requesting the entire index.
fetch(`${proxyUrl}${baseUrl}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-My-Custom-Header': `${apiKey}`,
'Access-Control-Allow-Origin': "*"
}
})
.then((response) => {
if (response.ok) {
response.json().then((json) => {
console.log(json.data);
let coinsData = json.data.coins;
if (coinsData.length > 0) {
var cryptoCoin = "";
}
coinsData.forEach((coin) => {
cryptoCoin = "<tr>";
cryptoCoin = `<td> ${coin.rank}</td>`;
cryptoCoin = `<td> ${coin.btcPrice} </td>`;
cryptoCoin = `<td> ${coin.name}</td>`;
cryptoCoin = `<td> $${Math.round(coin.price*100)/100}</td>`;
cryptoCoin = `<td> ${coin.symbol}</td>`;"<tr>";
});
document.getElementById("data").innerHTML = cryptoCoin;
});
}
})
.catch((error) => {
console.log(error);
});
CodePudding user response:
For your API in particular (Coinranker API), it looks like you can provide a limit attribute as a query parameter in your request like so:
fetch(`${proxyUrl}${baseUrl}?limit=5`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-My-Custom-Header': `${apiKey}`,
'Access-Control-Allow-Origin': "*"
}
})
Otherwise, you can use manually get the first 5 results by setting it's length, and slicing it:
coinsData.length = Object.keys(coinsData).length;
coinsData = Array.prototype.slice.call(coinsData, 5));