Skip to content

Instantly share code, notes, and snippets.

@jeremyckahn
Last active November 2, 2017 21:25
Show Gist options
  • Save jeremyckahn/0b098a395ac5a3bbf45f642eefc876fd to your computer and use it in GitHub Desktop.
Save jeremyckahn/0b098a395ac5a3bbf45f642eefc876fd to your computer and use it in GitHub Desktop.
A localstorage-backed cache wrapper for window.fetch
const fetchJson = (function () {
localStorage.cachedFetchResponses = localStorage.cachedFetchResponses || '{}';
let cache = localStorage.cachedFetchResponses;
const setCachedData = (key, data) => {
const parsedCache = JSON.parse(cache);
parsedCache[key] = data;
try {
localStorage.cachedFetchResponses = JSON.stringify(parsedCache);
} catch (e) {
console.error(e);
console.warn('Oh no something went wrong! Resetting localstorage cache...');
localStorage.cachedFetchResponses = '{}';
}
cache = localStorage.cachedFetchResponses;
return data;
};
const getCachedData = key => JSON.parse(cache)[key];
return (url) => {
if (getCachedData(url)) {
return new Promise(
(resolve, rej) => resolve(getCachedData(url))
);
} else {
return fetch(url).then(
res => res.json()
).then(
json => setCachedData(url, json)
);
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment