2

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

3
  • It seems to mostly work here: jsfiddle.net/jfriend00/xbjdp5qz. The source of the data does not appear to return different data if you make two closely spaced requests. But, with a small delay between requests I get a different response each time. Commented Feb 24, 2022 at 17:31
  • The occasional duplicates look like it may be a caching problem. If I change the URL to 'https://api.adviceslip.com/advice?t=' + Math.random(), I get a unique response every time. Commented Feb 24, 2022 at 17:33
  • OK, updated the jsFiddle here with the t=xxx fix: jsfiddle.net/jfriend00/a6yzvqsj Commented Feb 24, 2022 at 17:59

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.