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

84
Vistas
Fetch api return same data always

Every time one of my button is clicked, I trigger a call to the adviceslip API to get an advice data. I expect the payload to vary. But the exact same data is returned after each call.

I've tried to call getAdvice function as a callback but it didn't work.

Am I missing something?

'use strict'

const title = document.querySelector('.advice-title')
const desc = document.querySelector('.advice-text')
const btn = document.querySelector('.btn')



const getAdvice = async () =>{
    try{
        const response = await fetch('https://api.adviceslip.com/advice');
        if (!response.ok){
            throw new Error('Api connection problem')
        }
        const responseJson = await response.json();
        const data = responseJson.slip;

        const id = `ADVICE #${data.id}`;
        const advice = `"${data.advice}"`;

        title.textContent = id;
        desc.textContent = advice;

    }
    catch (e) {
        console.error(e)
    }

}



btn.addEventListener('click', () => {
    getAdvice()
})

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

0

There appears to be an issue with caching where multiple requests closely spaced in time from a web page will cause the same result to come back. If I add a uniquely changing value to the URL to defeat caching like this:

const response = await fetch('https://api.adviceslip.com/advice?t=' + Math.random());

Then, I get a unique response every time.

I experimented with sending various headers to disable caching instead of the t=xxx hack, but those headers trigger a CORs error and the fetch() does not succeed because custom headers like this don't pass the test for a "simple" CORS request and thus require pre-flight which the target site does not support. So, the ?t=xxx where xxx is different on each request seems to do the trick.

about 4 years ago · Juan Pablo Isaza Denunciar

0

I found this and it worked for me. Add const response = await fetch("https://api.adviceslip.com/advice", { cache: "no-cache" });

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