React Native - Fetch call cached

Andrew Ives picture Andrew Ives · Jul 23, 2015 · Viewed 19.5k times · Source

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

Answer

manosim picture manosim · Oct 10, 2015

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