use-fetch-with-callbacks
Version:
A powerful React hook for HTTP requests with comprehensive callback support, request chaining, and TypeScript integration
199 lines (198 loc) • 10.1 kB
TypeScript
/**
* Result object returned by the useFetchWithCallbacks hook
* @template T - The type of data expected from the API response
*/
export interface FetchResult<T> {
/** The response data from the API call, null if no data has been fetched yet */
response: T | null;
/** Whether a request is currently in progress */
loading: boolean;
/** Any error that occurred during the request, null if no error */
error: Error | null;
/** Whether at least one request has been completed (successfully or with error) */
requestCompleted: boolean;
/**
* Performs a GET request to the specified endpoint
* @param onSuccess - Optional callback executed when the request succeeds
* @param onError - Optional callback executed when the request fails
* @param onLoading - Optional callback executed when loading state changes
* @returns Promise that resolves when the request completes
*/
fetchData: (onSuccess?: (data: T) => void, onError?: (error: Error) => void, onLoading?: (loading: boolean) => void) => Promise<void>;
/**
* Performs a POST request to the specified endpoint
* @param data - The data to send in the request body
* @param onSuccess - Optional callback executed when the request succeeds
* @param onError - Optional callback executed when the request fails
* @param onLoading - Optional callback executed when loading state changes
* @returns Promise that resolves when the request completes
*/
postData: (data: unknown, onSuccess?: (data: T) => void, onError?: (error: Error) => void, onLoading?: (loading: boolean) => void) => Promise<void>;
/**
* Performs a PUT request to the specified endpoint
* @param data - The data to send in the request body
* @param onSuccess - Optional callback executed when the request succeeds
* @param onError - Optional callback executed when the request fails
* @param onLoading - Optional callback executed when loading state changes
* @returns Promise that resolves when the request completes
*/
putData: (data: unknown, onSuccess?: (data: T) => void, onError?: (error: Error) => void, onLoading?: (loading: boolean) => void) => Promise<void>;
/**
* Performs a DELETE request to the specified endpoint
* @param onSuccess - Optional callback executed when the request succeeds
* @param onError - Optional callback executed when the request fails
* @param onLoading - Optional callback executed when loading state changes
* @returns Promise that resolves when the request completes
*/
deleteData: (onSuccess?: (data: T) => void, onError?: (error: Error) => void, onLoading?: (loading: boolean) => void) => Promise<void>;
/**
* Performs a PATCH request to the specified endpoint
* @param data - The data to send in the request body
* @param onSuccess - Optional callback executed when the request succeeds
* @param onError - Optional callback executed when the request fails
* @param onLoading - Optional callback executed when loading state changes
* @returns Promise that resolves when the request completes
*/
patchData: (data: unknown, onSuccess?: (data: T) => void, onError?: (error: Error) => void, onLoading?: (loading: boolean) => void) => Promise<void>;
/**
* Performs multiple GET requests to different endpoints concurrently
* @param endpoints - Array of endpoint paths to fetch from
* @param onSuccess - Optional callback executed when all requests succeed
* @param onError - Optional callback executed when any request fails
* @param onLoading - Optional callback executed when loading state changes
* @returns Promise that resolves when all requests complete
*/
fetchMultipleData: (endpoints: string[], onSuccess?: (data: unknown[]) => void, onError?: (error: Error) => void, onLoading?: (loading: boolean) => void) => Promise<void>;
/**
* Provides a chainable interface for sequential operations
* @returns A chainable object with then, catch, and finally methods
*/
chain: () => ChainableRequest<T>;
}
/**
* Chainable request interface for sequential operations
* @template T - The type of data expected from the API response
*/
export interface ChainableRequest<T> {
/**
* Performs a GET request and returns a chainable object
* @param onSuccess - Optional callback executed when the request succeeds
* @param onError - Optional callback executed when the request fails
* @param onLoading - Optional callback executed when loading state changes
* @returns A chainable object for further operations
*/
fetch: (onSuccess?: (data: T) => void, onError?: (error: Error) => void, onLoading?: (loading: boolean) => void) => ChainableRequest<T>;
/**
* Performs a POST request and returns a chainable object
* @param data - The data to send in the request body
* @param onSuccess - Optional callback executed when the request succeeds
* @param onError - Optional callback executed when the request fails
* @param onLoading - Optional callback executed when loading state changes
* @returns A chainable object for further operations
*/
post: (data: unknown, onSuccess?: (data: T) => void, onError?: (error: Error) => void, onLoading?: (loading: boolean) => void) => ChainableRequest<T>;
/**
* Performs a PUT request and returns a chainable object
* @param data - The data to send in the request body
* @param onSuccess - Optional callback executed when the request succeeds
* @param onError - Optional callback executed when the request fails
* @param onLoading - Optional callback executed when loading state changes
* @returns A chainable object for further operations
*/
put: (data: unknown, onSuccess?: (data: T) => void, onError?: (error: Error) => void, onLoading?: (loading: boolean) => void) => ChainableRequest<T>;
/**
* Performs a DELETE request and returns a chainable object
* @param onSuccess - Optional callback executed when the request succeeds
* @param onError - Optional callback executed when the request fails
* @param onLoading - Optional callback executed when loading state changes
* @returns A chainable object for further operations
*/
delete: (onSuccess?: (data: T) => void, onError?: (error: Error) => void, onLoading?: (loading: boolean) => void) => ChainableRequest<T>;
/**
* Performs a PATCH request and returns a chainable object
* @param data - The data to send in the request body
* @param onSuccess - Optional callback executed when the request succeeds
* @param onError - Optional callback executed when the request fails
* @param onLoading - Optional callback executed when loading state changes
* @returns A chainable object for further operations
*/
patch: (data: unknown, onSuccess?: (data: T) => void, onError?: (error: Error) => void, onLoading?: (loading: boolean) => void) => ChainableRequest<T>;
/**
* Executes the chained operations sequentially
* @returns Promise that resolves when all operations complete
*/
execute: () => Promise<void>;
/**
* Adds a success callback to be executed after all operations complete
* @param callback - Function to execute on success
* @returns A chainable object for further operations
*/
then: (callback: (data: T) => void) => ChainableRequest<T>;
/**
* Adds an error callback to be executed if any operation fails
* @param callback - Function to execute on error
* @returns A chainable object for further operations
*/
catch: (callback: (error: Error) => void) => ChainableRequest<T>;
/**
* Adds a callback to be executed after all operations complete (success or error)
* @param callback - Function to execute finally
* @returns A chainable object for further operations
*/
finally: (callback: () => void) => ChainableRequest<T>;
}
/**
* Configuration options for the useFetchWithCallbacks hook
*/
export interface UseFetchOptions {
/** Base URL to prepend to all endpoint paths */
baseUrl?: string;
/** Additional headers to include in all requests */
headers?: Record<string, string> | Headers;
/** Request timeout in milliseconds (default: 10000) */
timeout?: number;
}
/**
* A React hook that provides fetch functionality with callback support for success, error, and loading states
*
* @template T - The type of data expected from the API response
* @param endpoint - The API endpoint path to make requests to
* @param options - Optional configuration including base URL and headers
* @returns An object containing response data, loading state, error state, and request methods
*
* @example
* Basic usage:
* ```typescript
* const { response, loading, error, fetchData } = useFetchWithCallbacks<User>('/users/1', {
* baseUrl: 'https://api.example.com',
* headers: { 'Authorization': 'Bearer token' }
* });
*
* // Fetch data with callbacks
* fetchData(
* (data) => console.log('Success:', data),
* (error) => console.error('Error:', error),
* (loading) => console.log('Loading:', loading)
* );
* ```
*
* @example
* Chaining operations:
* ```typescript
* const { chain } = useFetchWithCallbacks<User>('/users/1', {
* baseUrl: 'https://api.example.com'
* });
*
* // Chain multiple operations
* chain()
* .fetch((data) => console.log('Fetched:', data))
* .post({ name: 'John' }, (data) => console.log('Posted:', data))
* .put({ name: 'Jane' }, (data) => console.log('Updated:', data))
* .then((finalData) => console.log('All operations completed:', finalData))
* .catch((error) => console.error('Chain failed:', error))
* .finally(() => console.log('Chain finished'))
* .execute();
* ```
*/
declare const useFetchWithCallbacks: <T>(endpoint: string, options?: UseFetchOptions) => FetchResult<T>;
export default useFetchWithCallbacks;