Last active
November 2, 2017 21:25
-
-
Save jeremyckahn/0b098a395ac5a3bbf45f642eefc876fd to your computer and use it in GitHub Desktop.
A localstorage-backed cache wrapper for window.fetch
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
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