Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fetch data from API on button click – Javascript?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading