0.1.1 • Published 2 years ago

use-boxed-data v0.1.1

Weekly downloads
-
License
-
Repository
github
Last release
2 years ago

use-boxed-data

mit licence npm version bundlephobia

React data-fetching using boxed

use-boxed-data provides a simple data fetching hook inspired by SWR.

Design principles

  • Provide simple hook for cancellable requests that returns AsyncData.
  • compatibility with any request framework (fetch, axios, etc.).
  • Ability to caching requests with fallback support.
  • Automatic revalidation.
  • Mutate local cache immediately and revalidate from remote asynchronously.

What's in the box?

  • DataCacheConfig
  • useData

Installation

$ pnpm add use-boxed-data
# --- or ---
$ yarn add use-boxed-data
# --- or ---
$ npm install --save use-boxed-data

Usage

import { Future, Result } from '@swan-io/boxed';
import { AsyncData, AysncFetcher, useData } from 'use-boxed-data';

const fetcher: AsyncFetcher<CoolStuff> = (url: string, ...options: any[]) =>
  Future.make((resolve) =>
    fetch(url, options)
      .then((response) => response.json())
      .then((data) => resolve(Result.Ok(data)))
      .catch((err) => resolve(Result.Error(err))));

const MyAsyncComponent = () => {
  const { data, retry } = useData('/api/cool-stuff', fetcher);

  return data.match({
    Done: (result) =>
      result.match({
        Ok: (stuff) => {
          return <LoadedData cool={stuff} />;
        },
        Error: () => <Error onRetry={retry} />,
      }),
    Loading: () => <Loading />,
    NotAsked: () => <Loading />,
  });
}

Links