Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

229
Vistas
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?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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>

about 4 years ago · Juan Pablo Isaza Denunciar

0

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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda