UNPKG

rooks

Version:

Collection of awesome react hooks

85 lines (84 loc) 2.62 kB
/** * HTTP error interface extending Error with status information */ interface HttpError extends Error { status: number; statusText: string; } /** * Options for the useFetch hook */ interface UseFetchOptions extends Omit<RequestInit, 'signal'> { method?: string; headers?: Record<string, string>; body?: string | FormData | URLSearchParams; cache?: RequestCache; credentials?: RequestCredentials; mode?: RequestMode; redirect?: RequestRedirect; referrer?: string; referrerPolicy?: ReferrerPolicy; integrity?: string; keepalive?: boolean; onSuccess?: (data: any) => void; onError?: (error: Error) => void; onFetch?: () => void; } /** * Return value for the useFetch hook */ interface UseFetchReturnValue<T> { data: T | null; loading: boolean; error: Error | null; startFetch: () => Promise<void>; } /** * Hook for fetching data from URLs * * This hook provides a simple way to fetch data with proper TypeScript generics, * error handling, and automatic JSON parsing. It manages loading states and * provides a fetch function for manual data fetching. * * Note: This hook does not cache requests - each call triggers a fresh fetch. * The hook does not automatically fetch on mount - use the returned fetch function. * * @param url - The URL to fetch data from * @param options - Optional fetch configuration including callbacks * @returns Object containing data, loading state, error, and fetch function * * @example * ```tsx * function UserProfile({ userId }: { userId: string }) { * const { data: user, loading, error, fetch } = useFetch<User>( * `https://api.example.com/users/${userId}`, * { * headers: { 'Authorization': 'Bearer token' }, * onSuccess: (data) => console.log('User loaded:', data), * onError: (error) => console.error('Failed to load user:', error), * onFetch: () => console.log('Fetching user data...') * } * ); * * // Fetch data when component mounts or when needed * useEffect(() => { * fetch(); * }, [fetch]); * * if (loading) return <div>Loading...</div>; * if (error) return <div>Error: {error.message}</div>; * if (!user) return <div>No user data</div>; * * return ( * <div> * <h1>{user.name}</h1> * <p>{user.email}</p> * <button onClick={fetch}>Refresh</button> * </div> * ); * } * ``` */ declare function useFetch<T = unknown>(url: string, options?: UseFetchOptions): UseFetchReturnValue<T>; export { useFetch }; export type { UseFetchOptions, UseFetchReturnValue, HttpError };