I'm learning to use calls on APIs and I'm trying to get my API response to not return the same data over and over again, currently, it does despite using setInterval, I have tried changing the order and making it async but am currently not able to figure out how to change this.
The idea is to make an original call to the API on page load, then after 6 or so seconds, make the call again but change the response automatically hence the setInterval.
Here is my code:
const advice = document.getElementById("advice");
const adviceNum = document.getElementById("adviceNum");
const slip_id = Math.random() * 100;
console.log(slip_id)
fetch(`https://api.adviceslip.com/advice/${slip_id}`)
.then(response => {
return response.json();
})
.catch(error => {
console.log(error);
})
.then(data => {
console.log(data);
const returnedAdvice = data.slip.advice;
console.log(returnedAdvice);
const idAdvice = data.slip.id;
adviceNum.innerText = `ADVICE #${idAdvice}`;
advice.innerText = `"${returnedAdvice}"`;
setInterval(() => {
console.log(data);
const returnedAdvice = data.slip.advice;
console.log(returnedAdvice);
const idAdvice = data.slip.id;
adviceNum.innerText = `ADVICE #${idAdvice}`;
advice.innerText = `"${returnedAdvice}"`;
}, 8000)
})
Would appreciate any help on what I'm doing wrong here!
CodePudding user response:
Currently you're making a fetch request and when the data returns from that single request; you console.log etc.
Instead try the following, wrap your fetch request in the setInterval
setInterval(async function(){
const data = await fetch(`https://api.adviceslip.com/advice/${slip_id}`);
// check your response
// compute your values
// add them to the dom
}, 8000);