Introduction
A tiny bundle of pre-made fetcher functions for SWR, using fetch as the HTTP client.
Why?: SWR requires a "fetcher" function to make HTTP calls. Creating these for every project can be tedious, so this module provides a fetcher for every common HTTP method.
The fetchers are:
- tiny, lightweight, and portable
- Fetch implementation agnostic
- Fully typed, with bundled Typescript types
Basic Usage
Simply, install alongside any version of SWR,
# with npm
npm i swr @jych/swr-fetchers
# or with yarn
yarn add swr @jych/swr-fetchers
import the fetcher you need,
import useSWR from 'swr';
import { getFetcher } from '@jych/swr-fetchers';
and provide it to the useSWR
call.
export function Profile() {
const { data, error } = useSWR('/api/user', getFetcher);
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
That's it! You now have a pre-made fetcher for SWR.
Some more advanced use cases are shown below.
Using the Factory
This module also provides a factory that can be used to create new fetchers.
import { fetcherFactory } from '@jych/swr-fetchers';
const optionsFetcher = fetcherFactory({ method: 'OPTIONS' });
const getFetcherWithAuth = fetcherFactory({
headers: {
'Authorization': 'Bearer ...',
},
});
Typescript
The fetchers return a Promise<unknown>
when used with TypeScript, as the JSON body in not known.
You should validate the response and then cast it to the correct type:
interface UserData {
name: string;
}
// UserData Type Guard
const isUserData = (u: unknown): u is UserData => { /* ... */ };
export function Profile() {
const { data, error } = useSWR('/api/user', getFetcher);
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
if (!isUserData(data)) return <div>Server responded with an invalid repsponse</div>
return <div>hello {data.name}!</div>
}
In-fetcher validation
It's possible to move the typeguard within the fetcher itself, by appending the typeguard call to the fetcher:
import { getFetcher } from '@jych/swr-fetchers';
const userDataFetcher = getFetcher.then(data => isUserData(data)
? Promise.resolve(data)
: Promise.reject('Invalid reponse type')
);
Authors
This library was created by James Young. Contributions are welcome.
License
The MIT License.