react-fetch-client
v1.0.2
Published
Lightweight React hooks for data fetching with native fetch - simple factory-based API, TypeScript support, caching, and request cancellation
Maintainers
Readme
react-fetch-client
Lightweight React data fetching built on the native fetch API, with hooks, cache support, retry helpers.
Demo
Visit Demo link for working example of react-fetch-client package in action.
Install
npm install react-fetch-clientQuick start
import { createFetchClient, createFetchHooks } from 'react-fetch-client';
const client = createFetchClient({ baseURL: 'https://api.example.com' });
const { useGet, usePost } = createFetchHooks(client);Features, examples, and usage
1) Factory HTTP client (createFetchClient)
Example
import { createFetchClient } from 'react-fetch-client';
type User = { id: string; name: string };
const client = createFetchClient({
baseURL: 'https://api.example.com',
timeout: 30_000,
headers: { 'Content-Type': 'application/json' },
});
const users = await client.get<User[]>('/users');
const created = await client.post<User>('/users', { name: 'Ada' });Usage
- Use
client.get/post/put/patch/deletefor typed requests. - Add
onRequest,onResponse,onErrorin client config for global intercept logic. - Use
client.instance.request({...})for fully custom request config.
2) React hooks (createFetchHooks)
Example
import { createFetchClient, createFetchHooks } from 'react-fetch-client';
type User = { id: string; name: string };
type CreateUserInput = { name: string };
const client = createFetchClient({ baseURL: '/api' });
const { useGet, usePost } = createFetchHooks(client);
export function Users() {
const { data, loading, error, refetch, responseTimeInMillis } = useGet<User[]>('/users');
const { mutate: createUser, loading: creating } = usePost<User, CreateUserInput>('/users');
if (loading) return <p>Loading...</p>;
if (error) return <p>{error.message}</p>;
return (
<div>
<button disabled={creating} onClick={() => void createUser({ name: 'Grace' })}>
Add user
</button>
<button onClick={() => void refetch()}>Refresh</button>
<p>Last response: {responseTimeInMillis ?? 0}ms</p>
<ul>{data?.map((u) => <li key={u.id}>{u.name}</li>)}</ul>
</div>
);
}Usage
useGetsupportsimmediate,deps,params,retry,retryDelay,cachePolicy, andresponseType.- Mutation hooks are
usePost,usePatch,usePut,useDelete. - Use
abort({ clear: false })inuseGetto cancel without clearing previous data.
3) Request cancellation (isCanceledError)
Example
import { createFetchClient, isCanceledError } from 'react-fetch-client';
const client = createFetchClient({ baseURL: '/api' });
const controller = new AbortController();
const req = client.get('/users', { signal: controller.signal });
controller.abort();
try {
await req;
} catch (err) {
if (isCanceledError(err)) {
console.log('Request canceled safely');
}
}Usage
- Pass
signalin request config. - Use
isCanceledErrorto ignore user-triggered aborts in UI error handling.
4) Cache policies + cache adapters
Example
import {
createFetchClient,
createFetchHooks,
CachePolicy,
createLocalStorageCache,
} from 'react-fetch-client';
const client = createFetchClient({
baseURL: '/api',
cache: createLocalStorageCache(),
defaultCachePolicy: CachePolicy.NetworkFirst,
defaultCacheTTL: 60_000,
cachePolicies: {
'/products/*': CachePolicy.CacheFirst,
},
cacheTTLs: {
'/products/*': 5 * 60_000,
},
});
const { useGet } = createFetchHooks(client);
// Uses cache policy + TTL from client config:
const productsQuery = useGet('/products', { params: { page: 1 } });Usage
- Available policies:
NoCache,CacheFirst,NetworkFirst,NetworkOnly. - Adapters: memory (
createMemoryCache),localStorage,sessionStorage, IndexedDB. - Override per hook with
cachePolicy,cacheTTL,cacheKey,cacheAdapter.
API overview
| Export | Description |
| -------------------------------- | ------------------------------------------------------------------- |
| createFetchClient | Factory client with get/post/put/patch/delete |
| createFetchHooks | React hooks: useGet, usePost, usePatch, usePut, useDelete |
| CachePolicy | NoCache, CacheFirst, NetworkFirst, NetworkOnly |
| FetchError / isCanceledError | Structured errors + cancel detection |
| Cache adapters | memory, localStorage, sessionStorage, IndexedDB |
| Utilities | cache, retry, dedupe |
Development
npm install
npm run typecheck
npm test
npm run buildLicense
MIT - see LICENSE.
