Home > Back-end >  Why is my get request from a JSON online file won't refresh at new render?
Why is my get request from a JSON online file won't refresh at new render?

Time:09-02

I'm doing the folloing request over a json file stored on an azure blob.

const getDatas = () => {
    axios
      .get('https://randomname.blob.core.windows.net/public/data_home_page.json')
      .then(({ data }) => {
        setStats(data)}
        )
      .catch((er) => console.log('error'))
  }

I nested this function in a useEffect hook

useEffect(() => {
    getDatas()
  }, [])

It's working well as I can get the data and display it. My issue is that it's never refreshing at page/component render. The only solution is to clear cache.

How can I force the call to get fresh data withouth clearing all the user's cache ? And for a better understanding why does it go this way ?

CodePudding user response:

If you add the correct headers to your Axios call this should disable the cache.

headers: {
    'Cache-Control': 'no-cache',
    'Pragma': 'no-cache',
    'Expires': '0',
}

Full Axios example

axios.get(`https://randomname.blob.core.windows.net/public/data_home_page.json`, {
    headers: {
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
        'Expires': '0',
    }
    })
    .then(({ data }) => {
    setStats(data);
    })
    .catch((er) => console.log("error"));
};

Example: https://codesandbox.io/s/flamboyant-resonance-dhq2fi?file=/src/App.js

  • Related