34

I am building an app in react native which makes fetch calls that rely on the most up to date information from the server. I have noticed that it seems to cache the response and if i run that fetch call again it returns the cached response rather than the new information from my server.

My function is as follows:

goToAll() {
  AsyncStorage.getItem('FBId')
    .then((value) => {
      api.loadCurrentUser(value)
        .then((res) => {
          api.loadContent(res['RegisteredUser']['id'])
            .then((res2) => {
              console.log(res2);
              this.props.navigator.push({
                component: ContentList,
                title: 'All',
                passProps: {
              content: res2,
            user: res['RegisteredUser']['id']
          }
        })
      });
    });
  })
  .catch((error) => {console.log(error);})
  .done();
}

and the function from api.js im calling is as follows:

loadContent(userid){
  let url = `http://####.com/api/loadContent?User_id=${userid}`;
  return fetch(url).then((response) => response.json());
}
knowbody
  • 8,106
  • 6
  • 45
  • 70
Andrew Ives
  • 467
  • 2
  • 6
  • 12

3 Answers3

56

You can set a Header to prevent the request from being cached. Example below:

return fetch(url, {
  headers: {
    'Cache-Control': 'no-cache'
  }
}).then(function (res) {
  return res.json();
}).catch(function(error) {
  console.warn('Request Failed: ', error);
});
manosim
  • 3,630
  • 12
  • 45
  • 68
  • 9
    “`no-cache` doesn't mean "don't cache", it means it must check (or "revalidate" as it calls it) with the server before using the cached resource.” Use `no-store` instead. src: https://jakearchibald.com/2016/caching-best-practices/ – Jules Sam. Randolph Jul 19 '18 at 19:17
31

Manosim's answer didn't work for me, but put me on the path to a solution that did work:

fetch(url, {
  headers: {
    'Cache-Control': 'no-cache, no-store, must-revalidate',
    'Pragma': 'no-cache',
    'Expires': 0
  }
})

This nailed it.

lance.dolan
  • 3,493
  • 27
  • 36
1

I had a similar problem with react native (Android) and fetch using clojurescript (instead of js). Adding :cache "no-store" (not in the header) stopped the behavior (caching fetch data on Android App).

I think the code in js should be something like:

fetch(url, {'cache':'no-store'})

specs fetch cache-mode

fgui
  • 1,564
  • 1
  • 13
  • 14