Skip to content

Instantly share code, notes, and snippets.

@dslounge
Last active May 6, 2020 08:31
Show Gist options
  • Save dslounge/18e555250a8df1f8218d702b21910eeb to your computer and use it in GitHub Desktop.
Save dslounge/18e555250a8df1f8218d702b21910eeb to your computer and use it in GitHub Desktop.
cache fetch in React Native
export const cachedFetch = url => {
const key = `@MySuperStore:${url}`;
return AsyncStorage.getItem(key)
.then(data => {
if (!data) {
return Promise.reject("no data found in async storage");
}
console.log("found data on disk");
return JSON.parse(data);
})
.catch(() => {
console.log("didn't find data on disk, fetching");
return fetch(url).then(response => {
if (response.ok) {
return response.json().then(data => {
AsyncStorage.setItem(key, JSON.stringify(data));
return data;
});
}
return Promise.reject("unable to load data");
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment