react-fetch-pilot
v1.0.1
Published
A flexible React data-fetching custom hook
Maintainers
Readme
react-fetch-pilot
A lightweight, feature-rich React hooks library for API data fetching and mutations with built-in retry logic, polling, and window focus refetching.
Features
- 🚀 Simple API - Intuitive hooks for queries and mutations
- 🔄 Auto Retry - Built-in exponential backoff retry logic
- ⏰ Polling - Configurable refetch intervals
- 🎯 Window Focus Refetch - Automatically refetch when tab regains focus
- 🛡️ Abort Support - Automatic request cancellation on unmount
- 📦 Zero Dependencies - Only requires React 16.8+
- 🎣 TypeScript Ready - Full type support out of the box
Installation
npm install react-fetch-pilot
# or
yarn add react-fetch-pilotuseDataFetcher (For GET/Queries)
import { useDataFetcher } from 'react-fetch-pilot';
function UserList() {
const { data, error, loading, refetch } = useDataFetcher(
[], // dependencies array
async (signal) => {
const response = await fetch('/api/users', { signal });
const data = await response.json();
return { data };
},
{
enabled: true,
refetchInterval: 5000,
refetchOnWindowFocus: true,
retry: 3,
retryDelay: 1000,
onSuccess: (data) => console.log('Success:', data),
onError: (error) => console.error('Error:', error)
}
);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
{data?.map(user => <div key={user.id}>{user.name}</div>)}
<button onClick={refetch}>Refresh</button>
</div>
);
}useMutation (For POST/PUT/DELETE)
import { useMutation } from 'react-fetch-pilot';
function CreateUser() {
const { execute, data, error, loading } = useMutation(
async (userData) => {
const response = await fetch('/api/users', {
method: 'POST',
body: JSON.stringify(userData),
headers: { 'Content-Type': 'application/json' }
});
const data = await response.json();
return { data };
},
{
onSuccess: (data) => console.log('User created:', data),
onError: (error) => console.error('Failed:', error)
}
);
const handleSubmit = async (e) => {
e.preventDefault();
try {
const result = await execute({ name: 'John Doe', email: '[email protected]' });
console.log('Created user:', result);
} catch (error) {
console.error('Submission failed:', error);
}
};
return (
<form onSubmit={handleSubmit}>
<button type="submit" disabled={loading}>
{loading ? 'Creating...' : 'Create User'}
</button>
</form>
);
}API Reference
UseDataFetcher
useDataFetcher<TData, TError>(
dependencies: DependencyList,
apiFunction: (signal: AbortSignal) => Promise<{ data: TData }>,
options?: UseDataFetcherOptions
): UseDataFetcherResultOptions
| Option | Type | Default | Description |
| ------ | ---- | ------- | ----------- |
| enabled | boolean | true | Enable/disable automatic fetching |
| refetchInterval | number | undefined | Polling interval in milliseconds |
| refetchOnWindowFocus | boolean | false | Refetch when window regains focus |
| retry | number | 0 | Number of retry attempts on failure |
| retryDelay | number | 1000 | Base delay between retries (ms) |
| onSuccess | (data) => void | - | Callback on successful fetch |
| onError | (error) => void | - | Callback on fetch error |
useMutation
useMutation<TData, TArgs, TError>(
apiFunction: (...args: TArgs) => Promise<{ data: TData }>,
options?: UseMutationOptions
): UseMutationResult
Returns: { execute, data, error, loading }
Examples:
Basic Fetch with Dependencies:
const [userId, setUserId] = useState(1);
const { data, loading } = useDataFetcher(
[userId],
async (signal) => {
const res = await fetch(`/api/users/${userId}`, { signal });
return { data: await res.json() };
}
);
Manual Execution Only:
const { data, loading, refetch } = useDataFetcher(
[],
fetchUsers,
{ enabled: false }
);
<button onClick={refetch}>Load Users</button>
Error Handling with Retry:
const { data, error, loading } = useDataFetcher(
[],
fetchCriticalData,
{
retry: 5,
retryDelay: 2000,
onError: (err) => {
console.error('Failed after retries:', err);
}
}
);TypeScript Support
The library is written in TypeScript and includes type definitions. You can use generics to type your data:
interface User {
id: number;
name: string;
email: string;
}
const { data, error } = useDataFetcher<User>(
[],
async (signal) => {
const res = await fetch('/api/user', { signal });
return { data: await res.json() };
}
);Browser Support
- Chrome 66+
- Firefox 57+
- Safari 12.1+
- Edge 79+
📄 License
Universal Unit is released under the MIT License.
You are free to use, modify, distribute, and integrate the package into your projects according to the terms of the MIT License.
