Reputation: 39
I want to fetch data (particularly market cap)from api and display it inside my div. But my html diplays no data on execution. What could I be doing wrong?
<text id="result"></text>
<script>
// API for get requests
let fetchRes = fetch(
"https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX");
// fetchRes is the promise to resolve
// it by using.then() method
fetchRes.then((res) => res.json())
.then((result) => {
console.log(result);
document.getElementById('result').innerHTML = result.config.data.0.market_cap;
})
.catch(error => {
console.log(error);
})
</script>
Upvotes: 2
Views: 1094
Reputation: 2255
You can make it cleaner and simpler:
const fetchData = async(url) => (await fetch(url)).json();
fetchData("https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX")
.then(res => {
result.innerText = res.data[0].market_cap;
})
.catch(err => {
console.log(err);
});
<text id="result"></text>
Upvotes: 1
Reputation: 91
Use result.config.data[0].market_cap; instead of result.config.data.0.market_cap;
let fetchRes = fetch(
"https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX");
// fetchRes is the promise to resolve
// it by using.then() method
fetchRes.then((res) => res.json())
.then((result) => {
console.log(result);
document.getElementById('result').innerHTML = result.config.data[0].market_cap;
})
.catch(error => {
console.log(error);
});
Upvotes: 1
Reputation: 165
I am using jQuery Framework to do this easily. Check the code below.
<script>
$.get(
"https://api.lunarcrush.com/v2",
{
data: "assets",
key: "n8dyddsipg5611qg6bst9",
symbol: "AVAX"
},
function (result){
data = JSON.parse(result);
}
);
</script>
You can use jQuery by adding the following code in your <head>
tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Upvotes: 1
Reputation: 44706
Two suggestions:
.then()
directly to the fetch()
?result.data[0].market_cap
.// API for get requests
let fetchRes = fetch("https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX")
.then((res) => res.json())
.then((result) => {
console.log(result);
document.getElementById('result').innerHTML = result.data[0].market_cap;
})
.catch(error => {
console.log(error);
})
<text id="result"></text>
Aside: you should probably invalidate your API key that you've included here, as it's now out in public and can be used to forge requests as you to this API.
Upvotes: 3