Issue
I’ve got this part of code:
fetch(`https/someapi.com/data`)
.then(response => {
return response.json()
}).then(randomProduct => {
document.querySelector('#list').innerHTML = `
<span>${randomProduct.value}</span>
<button id="refresh-button" type="button">Refresh</button>
`;
var clickOnButton = document.querySelector("#refresh-button");
clickOnButton.addEventListener("click", () => {
})
})
How to I make this onClick event refresh the data the I read from API and display a new one?
Solution
you can wrap it all in a function and call it like this
const fakeApi = () => new Promise(resolve => setTimeout(() => resolve({
value: Math.floor(Math.random() * 100)
}), 500))
const getData = () => fakeApi().then(randomProduct => {
document.querySelector('#main').innerHTML = `
<span>${randomProduct.value}</span>
<button id="refresh-button" type="button" onclick="getData()">Refresh</button>`
})
getData()
<div id="main"></div>
Answered By – R4ncid
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0