Skip to content

Instantly share code, notes, and snippets.

@developit
Created August 28, 2016 15:36
Show Gist options
  • Save developit/2345d69e4b7a778bcdbfad2c1ccd0833 to your computer and use it in GitHub Desktop.
Save developit/2345d69e4b7a778bcdbfad2c1ccd0833 to your computer and use it in GitHub Desktop.
Dead simple fetch caching

Dead Simple Fetch Caching

Wrap fetch() in a memoize.

Not only does this cache repeated requests for the same resource, it also de-dupes concurrent requests!

Notes:

  • Caching the raw response object doesn't work, since the response body is a stream and can thus only be read once
  • Instead, cache your already read body (optionally still including the original request, just read the body prior)
const CACHE = {};
const MAX_AGE = 60000; // 1m
function cachedFetch(url, opts) {
let cached = CACHE[url];
if (cached && Date.now()-cached.time<MAX_AGE) return cached;
let req = fetch(url, opts).then( r => r.json() );
req.time = Date.now();
// do fancy stuff
return (CACHE[url] = req);
}
@eagl3s1ght
Copy link

Great thanks for the idea, using a rewritten version of your code for CoOptimus-Enhanced-UX

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment