I'm building an app in React Native that makes a get call that relies on the server for the latest information. I noticed that it seems to cache the response, and if I run the fetch call again, it returns the cached response instead of the new information from the 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(); }
The api.js function I called is as follows:
loadContent(userid){ let url = `http://####.com/api/loadContent?User_id=${userid}`; return fetch(url).then((response) => response.json()); }
P粉5485126372023-10-22 21:31:24
Manosim's answer didn't work for me, but put me on a path to a solution that didwork:
fetch(url, { headers: { 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': 0 } })
This solved the problem.
P粉7382485222023-10-22 12:07:09
You can set headers
to prevent requests 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); });