Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

83
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!