Skip to content

Instantly share code, notes, and snippets.

@akshar-dave
Created November 6, 2023 10:44
Show Gist options
  • Save akshar-dave/27d04103e585d0129cc7225221218f49 to your computer and use it in GitHub Desktop.
Save akshar-dave/27d04103e585d0129cc7225221218f49 to your computer and use it in GitHub Desktop.
Cache API Results
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