I want to fetch data from API and show it on HTML by elementID with JavaScript, Please help what I wrong in this code below.
<div id="priceChange"></div>
<script>
setInterval(tradestime, 5000);
function tradestime(){
fetch("https://api.binance.com/api/v1/ticker/24hr?symbol=LTCUSDT")
.then(
(res) => {
const data = res.json();
}
)
document.getElementById("priceChange").innerHTML = data.PriceChange;
}
</script>
Please fix this code.
You should use res.json() because you want data in JSON format. which will return promise and then you can get data. You should read fetch docs
fetch("https://api.binance.com/api/v1/ticker/24hr?symbol=LTCUSDT")
.then(res => res.json())
.then(data => el.innerHTML = data.priceChange)
key should be priceChange not PriceChange.
You can use parseFloat + toFixed as:
el.innerHTML = Number.parseFloat(data.priceChange).toFixed(2);
setInterval(tradestime, 5000);
const el = document.getElementById("priceChange");
function tradestime() {
fetch("https://api.binance.com/api/v1/ticker/24hr?symbol=LTCUSDT")
.then(res => res.json())
.then(data => el.innerHTML = data.priceChange)
}
<div id="priceChange"></div>
You can also use async-await here
setInterval( tradestime, 5000 );
const el = document.getElementById( "priceChange" );
async function tradestime() {
const res = await fetch( "https://api.binance.com/api/v1/ticker/24hr?symbol=LTCUSDT" )
const data = await res.json();
el.innerHTML = data.priceChange;
}
<div id="priceChange"></div>