use-api-handler
v1.0.8
Published
A versatile hook for handling API requests in React applications.
Downloads
5
Maintainers
Readme
use-api-handler
A versatile hook for handling API requests in React applications.
Table of Contents
Installation
npm install use-api-handler
Usage
import React from 'react';
import useApiHandler from 'use-api-handler';
function App() {
const { data, loading, error, sendRequest } = useApiHandler('https://api.example.com/data');
return (
<div>
{loading && <p>Loading...</p>}
{error && <p>Error: {error.message}</p>}
{data && <pre>{JSON.stringify(data, null, 2)}</pre>}
<button onClick={() => sendRequest('GET')}>Fetch Data</button>
</div>
);
}
export default App;
Features
Simplifies API requests in React applications Pagination support with fetchPaginatedData function Caching of API responses using fetchCachedData Error handling and automatic retries with sendRetriableRequest Custom request headers and authentication support Clean cancellation and cleanup on unmounting
Examples
Check out the examples directory for more usage examples and integration scenarios.
API Reference
useApiHandler(initialUrl, initialData, debounceDelay) Parameters initialUrl: Initial API endpoint URL. initialData (optional): Initial data for the hook. Default: null. debounceDelay (optional): Delay in milliseconds for URL debouncing. Default: 300. Returns An object with the following properties and functions:
data: The fetched data. loading: A boolean indicating if the request is in progress. error: An error object if the request encountered an error. setUrl(url): Update the API endpoint URL. sendRequest(method, requestData, requestConfig): Send a custom API request. fetchPaginatedData(page, pageSize): Fetch paginated data. fetchCachedData(): Fetch cached data or perform a new request if not cached. sendAuthenticatedRequest(method, requestData, token): Send an authenticated API request. sendRetriableRequest(method, requestData, requestConfig, retries, delay): Send a retriable API request.
Contributing
Contributions are welcome! Please read CONTRIBUTING.md for details on how to contribute to this project.
License
This project is licensed under the MIT License. See LICENSE for more information.