Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Fetch call cached

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());
}
like image 720
Andrew Ives Avatar asked Jul 23 '15 16:07

Andrew Ives


3 Answers

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);
});
like image 108
manosim Avatar answered Nov 16 '22 06:11

manosim


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.

like image 34
lance.dolan Avatar answered Nov 16 '22 06:11

lance.dolan


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

like image 1
fgui Avatar answered Nov 16 '22 06:11

fgui