Yunus Emre Arslan
Yunus Emre Arslan

Reputation: 53

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()
})

Upvotes: 2

Views: 2278

Answers (2)

Marcos Fitzsimons
Marcos Fitzsimons

Reputation: 11

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

Upvotes: 1

jfriend00
jfriend00

Reputation: 708046

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.

Upvotes: 2

Related Questions