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());
}
                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'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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With