React Native - Fetch call cached

不问归期 提交于 2020-01-11 18:50:49

问题


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

回答1:


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



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/31593213/react-native-fetch-call-cached

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!