fetch("https://api.coingecko.com/api/v3/simple/price?ids=Bitcoin%2Cdai%2Csolana&vs_currencies=usd&include_market_cap=true&include_24hr_vol=true")
.then((data) => {
console.log(data);
return data.json();
})
.then((completeData) => {
console.log(completeData)
if(completeData.length > 0) {
var cryptoCoin = ""
}
for (var i=0; i = completeData.length; i++) {
completeData.forEach(completeData[i])
cryptoCoin += "<tr>"
cryptoCoin += `<td> ${completeData.bitcoin} </td>`;
cryptoCoin += `<td> ${completeData.usd_market_cap} </td>`;
cryptoCoin += `<td> ${completeData.usd_24h_vol} </td>`;
cryptoCoin += `<td> ${completeData.usd} </td>`;
}
document.getElementById("data").innerHTML = cryptoCoin;
})
.catch ((err) => {
console.log(err)
})
How would i display this to my HTML it comes back on my HTML as undefined what am i missing. I'm new to javascript so trying to understand.
There are a few issues with your code.
First of all, you declare the cryptoCoin variable inside the if and then when the if bracket closes you start your for loop. You should have the declaration of the variable within the same scope or higher one like below.
Second, you should not use both the for loop and the forEach which you are currently using in a completely wrong way.
Third, i should be less than the completeData.length not equal.
Finally, you should probably close the table row.
Should look more like this:
if (completeData.length > 0) {
var cryptoCoin = "";
for (var i=0; i < completeData.length; i++) {
cryptoCoin += "<tr>";
cryptoCoin += `<td> ${completeData[i].bitcoin} </td>`;
cryptoCoin += `<td> ${completeData[i].usd_market_cap} </td>`;
cryptoCoin += `<td> ${completeData[i].usd_24h_vol} </td>`;
cryptoCoin += `<td> ${completeData[i].usd} </td>`;
cryptoCoin += "</tr>";
}
document.getElementById("data").innerHTML = cryptoCoin;
}
You have some mistakes in your code. i fixed that it would be work and you see that it push strings in your table. the rest is homework for you ;-)
fetch("https://api.coingecko.com/api/v3/simple/price?ids=Bitcoin%2Cdai%2Csolana&vs_currencies=usd&include_market_cap=true&include_24hr_vol=true")
.then((data) => {
return data.json();
})
.then((completeData) => {
let table = document.querySelector('table');
let keys = Object.keys(completeData)
console.log(keys)
for (var i=0; i < keys.length; i++) {
let usd = completeData[keys[i]].usd;
let usd_market_cap = completeData[keys[i]].usd_market_cap
let usd_24h_vol = completeData[keys[i]].usd_24h_vol
let row = `<td> ${usd} </td> <td> ${usd_market_cap} </td> <td> ${usd_24h_vol} </td>`;
let tr = document.createElement('tr');
tr.innerHTML = row
table.appendChild(tr)
}
})
.catch ((err) => {
console.log(err)
})
<table border="1" id="data">
<th>1</th>
<th>2</th>
<th>3</th>
</table>