0.0.3 • Published 5 years ago

use-cached-promise v0.0.3

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

use-cached-promise

React hooks that allows to you to use cached promise factory.

NPM

Install

yarn add use-cached-promise

Usage

Without cache

import React, { Component } from 'react'
import useCachedPromise, { RESPONSE_STATUS } from "use-cached-promise";

const fetchIp = () =>
  fetch("https://httpbin.org/get")
    .then(r => r.json())
    .then(({ origin }) => origin);

const options = {
  cacheKey: "ipStore"
};

function IpInfo() {
  const { response, status } = useCachedPromise(fetchIp, options);

  return (
    <div className="App">
      <h1>{status === RESPONSE_STATUS.pending && "Loading..."}</h1>
      <h1>{status === RESPONSE_STATUS.success && `Your ip is ${response}`}</h1>
    </div>
  );
}

With cache

import React, { Component } from 'react'
import useCachedPromise, { RESPONSE_STATUS, LocalStorgeCacheAdapter } from "use-cached-promise";

const fetchIp = () =>
  fetch("https://httpbin.org/get")
    .then(r => r.json())
    .then(({ origin }) => origin);

const options = {
  cacheKey: "ipStore",
  cacheAdapter: new LocalStorgeCacheAdapter()
};

function IpInfo() {
  const { response, status } = useCachedPromise(fetchIp, options);

  return (
    <div className="App">
      <h1>{status === RESPONSE_STATUS.pending && "Loading..."}</h1>
      <h1>{status === RESPONSE_STATUS.success && `Your ip is ${response}`}</h1>
    </div>
  );
}

Response Status types

  • idle
  • pending
  • success
  • failure

Cache adapters

  • MemoryCacheAdapter
import { MemoryCacheAdapter } from 'use-cached-promise';
  • LocalStorageCacheAdapter
import { LocalStorageCacheAdapter } from 'use-cached-promise';

License

MIT © chirag

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago

0.0.0

5 years ago