-
-
Save arjndr/1ed94a191bb6066f492e3cf6413f19f1 to your computer and use it in GitHub Desktop.
cache fetch in React Native
This file contains hidden or 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