Aspida-SWR Adapter
Just one function, which adapt
This enables Conditional or Depentent Fetching in easy, DRY, and null-safe way.
This library doesn't have dependency on SWR.
However, if you use SWR, we recommend you to use ver 2.x
Install
npm i aspida-swr-adapter
Quick Start
This library has only one API
aspidaToSWR(api, method, extra, (fn, extra, ...params) => ..);
whose return values [getKey, fetcher]
(in tuple) are ready to pass to useSWR
, useSWRInfinite
, and useSWRImmutable
.
For example...
Simple
const args = aspidaToSWR(
userId !== undefined && apiClient.users._userId(userId),
"$get",
isValidToken(token) && { token },
(fn, { token }) => fn( query: { token } )
);
const { data } = useSWR(...args);
Keys with Parameters
const [getKey, fetcher] = aspidaToSWR(
userId !== undefined &&
apiClient.users._userId(userId).posts,
"$get",
isValidToken(token) && { token },
(fn, { token }, page: number) => fn({ query: { token, page } })
);
const { data: pagesData, setSize } = useSWRInfinite(
(pageIndex) => getKey(pageIndex),
fetcher,
{ initialSize: 2 }
);
Let's take a closer look.
const [getKey, fetcher] = aspidaToSWR(
userId !== undefined &&
apiClient.users._userId(userId).posts,
"$get",
isValidToken(token) &&
{ token },
(fn, { token }, page: number) => fn({ query: { token, page } })
);
const { data: pagesData, setSize } = useSWRInfinite(
(pageIndex) => getKey(pageIndex),
fetcher,
{ initialSize: 2 }
);
Examples
In examples/next-swr
subproject, You can find some example code (using Next.js) like below.