0.10.6 • Published 1 year ago

react-swr-store v0.10.6

Weekly downloads
8
License
MIT
Repository
github
Last release
1 year ago

react-swr-store

React bindings for swr-store

NPM JavaScript Style GuideOpen in CodeSandbox

Install

npm install --save swr-store react-swr-store
yarn add swr-store react-swr-store

Usage

import React, { Suspense } from 'react';
import { createSWRStore } from 'swr-store';
import { useSWRStore, SWRStoreRoot } from 'react-swr-store';

const API = 'https://dog.ceo/api/breed/';
const API_SUFFIX = '/images/random';

interface APIResult {
  message: string;
  status: string;
}

const dogAPI = createSWRStore<APIResult, [string]>({
  key: (breed: string) => breed,
  get: async (breed: string) => {
    const response = await fetch(`${API}${breed}${API_SUFFIX}`);
    return (await response.json()) as APIResult;
  },
  revalidateOnFocus: true,
  revalidateOnNetwork: true,
});

function DogImage(): JSX.Element {
  const data = useSWRStore(dogAPI, ['shiba'], {
    suspense: true,
  });

  return <img src={data.message} alt={data.message} />;
}

function Trigger(): JSX.Element {
  return (
    <button
      type="button"
      onClick={() => {
        dogAPI.trigger(['shiba']);
      }}
    >
      Trigger
    </button>
  );
}

export default function App(): JSX.Element {
  return (
    <SWRStoreRoot>
      <Trigger />
      <div>
        <Suspense fallback={<h1>Loading...</h1>}>
          <DogImage />
        </Suspense>
      </div>
    </SWRStoreRoot>
  );
}

API

<SWRStoreRoot>

Must be located at the root of the app/tree.

useSWRStore(store, args, options)

Subscribes to an SWR store, passing args, which are received by the corresponding store for data-fetching and cache updates.

options has the following properties:

  • suspense: When true, suspends the component when receiving the result, if the result status is 'pending' until the result resolves,where useSWRStore returns the resolved data. Otherwise, useSWRStore returns the result. Defaults to false.
  • initialData: Allows lazy hydration when reading the store. If the store does not have cache, initialData hydrates the cache and attempts a revalidation. If no initialData is provided, defaults to store's options.initialData.
  • shouldRevalidate: If true, goes through the revalidation process when reading through the cache. Defaults to true.

License

MIT © lxsmnsyc

0.10.5

1 year ago

0.10.6

1 year ago

0.10.3

2 years ago

0.10.4

2 years ago

0.10.2

2 years ago

0.10.0

2 years ago

0.9.4

3 years ago

0.9.3

3 years ago

0.9.0

3 years ago

0.9.2

3 years ago

0.9.1

3 years ago

0.8.1

3 years ago

0.8.0

3 years ago

0.8.2

3 years ago

0.7.1

3 years ago

0.7.0

3 years ago

0.6.0

3 years ago

0.5.2

3 years ago

0.5.1

3 years ago

0.5.0

3 years ago

0.4.0

3 years ago

0.3.0

4 years ago

0.2.0

4 years ago

0.1.0

4 years ago