Last active
May 6, 2020 08:31
-
-
Save dslounge/18e555250a8df1f8218d702b21910eeb to your computer and use it in GitHub Desktop.
cache fetch in React Native
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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