Home > Software design >  How to fetch data from API on button click - Javascript?
How to fetch data from API on button click - Javascript?

Time:05-22

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?

CodePudding user response:

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>

CodePudding user response:

I'm not sure if I understood your question correctly, but from what I'be got you want to edit only the data on fetch no need to create a button and a listener every time. Place the fetch inside a dedicated function which is called onClick of the button in the fetch just edit the value.

CodePudding user response:

first you need a button to make the fetch request

const fetchDataBtn = document.querySelector('#fetchdata')
const result = document.querySelector('#result')

// gets data from API and sets the content of #result div
const getData = function() {
  result.innerText = 'Loading....'
  fetch('https://dummyjson.com/products')
    .then(res => res.json())
    .then(data => {
      result.innerText = JSON.stringify(data, null, 2)
    })
    .catch(error => console.log(error))
}

// add event listener for #fetchdata button
fetchDataBtn.addEventListener('click', getData)

const fetchDataBtn = document.querySelector('#fetchdata')
    const result = document.querySelector('#result')
    
    // gets data from API and sets the content of #result div
    const getData = function() {
      result.innerText = 'Loading....'
      fetch('https://dummyjson.com/products')
        .then(res => res.json())
        .then(data => {
          result.innerText = JSON.stringify(data, null, 2)
        })
        .catch(error => console.log(error))
    }
    
    // add event listener for #fetchdata button
    fetchDataBtn.addEventListener('click', getData)
<button id="fetchdata">FETCH</button>
<div id="result"></div>

  • Related