Skip to content
Helper for caching `fetch` requests in localStorage
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
.babelrc
.editorconfig feat: initial Commit Mar 26, 2018
.eslintrc fix: linter config Mar 26, 2018
.esprintrc
.gitignore feat: initial Commit Mar 26, 2018
.npmignore feat: initial Commit Mar 26, 2018
.vcmrc
LICENSE feat: initial Commit Mar 26, 2018
README.md
package.json 1.1.0 May 4, 2018
projectz.cson
webpack.config.js fix: updated webpack config Mar 26, 2018
yarn.lock none: adding esprint May 3, 2018

README.md

Cache Fetch

Helper for caching fetch calls in localStorage

Nodei.co badge
Travis CI Build Status NPM version NPM downloads Dependency Status

Installation

yarn add cached-fetch

or

npm install cached-fetch

Usage

import cacheFetch from 'cache-fetch';

...
/**
* Cached fetch wrapper/helper
* @param {string} url URL being fetched
* @param {*} options fetch options
* @param {number} expiry time in seconds for caching, default = 300 (5 minutes)
*/
const url = 'API PATH';
const options = {
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  }
};

const response = cacheFetch(url, options);
// or
const response = cacheFetch(url, options, 600);

return response.json();
...

Offline handling (Great for PWA's)

Assuming the API call has been made already and your application has been setup for offline usage, you can use this helper to retrieve the saved data instead of using the cacheFetch which will invalidate if cache time has elapsed.

import cacheFetch, { offlineResponse } from 'cache-fetch';

/* Will need proper implimentation based on application setup */
let online = true;
window.addEventListener('online', () => online = true);
window.addEventListener('offline', () => online = false);
...
/**
* Cached fetch wrapper/helper
* @param {string} url URL being fetched
* @param {*} options fetch options
* @param {number} expiry time in seconds for caching, default = 300 (5 minutes)
*/
const url = 'API PATH';
const options = {
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  }
};

const response = online ? cacheFetch(url, options) : offlineResponse(url);
// or
const response = online ? cacheFetch(url, options, 600) : offlineResponse(url);

return response.json();
...

History

Discover the release history by heading on over to the releases page.

License

Unless stated otherwise all works are:

  • Copyright © 2018+ Reme Le Hane

and licensed under:

You can’t perform that action at this time.