Created
November 6, 2023 10:44
-
-
Save akshar-dave/27d04103e585d0129cc7225221218f49 to your computer and use it in GitHub Desktop.
Cache API Results
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
const loadData = async (url) => { | |
var data = localStorage.getItem(url); | |
if (data) { // check if expired | |
data = JSON.parse(data); | |
if (Date.now() - data.timestamp > 600000) { // 10mins | |
localStorage.removeItem(url); | |
data = null; | |
} | |
} | |
if (!data) { // load fresh | |
data = await fetch(url).then(response => response.json()); | |
data.timestamp = Date.now(); | |
localStorage.setItem(url, JSON.stringify(data)); | |
} | |
return data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment