UNPKG

@supunlakmal/hooks

Version:

A collection of reusable React hooks

36 lines (35 loc) 1.54 kB
type FetchStatus = 'idle' | 'loading' | 'success' | 'error'; interface UseCachedFetchOptions { /** Time-to-live for cache entries in milliseconds. Defaults to 5 minutes. */ ttl?: number; /** Standard fetch options (method, headers, body, etc.). */ fetchOptions?: RequestInit; /** Function to generate a unique cache key from the URL and options. Defaults to using the URL. */ getCacheKey?: (url: string, options?: RequestInit) => string; /** If true, prevents fetching if data exists in cache, even if expired. Defaults to false. */ cacheOnlyIfFresh?: boolean; } interface UseCachedFetchResult<T> { data: T | undefined; error: Error | undefined; status: FetchStatus; isLoading: boolean; isSuccess: boolean; isError: boolean; isIdle: boolean; /** Function to manually trigger a refetch, optionally bypassing cache. */ refetch: (options?: { ignoreCache?: boolean; }) => Promise<void>; } /** * Fetches data like `useFetch` but includes a simple in-memory cache * to avoid redundant requests for the same URL within a configurable TTL. * * @template T The expected type of the data to be fetched. * @param url The URL to fetch data from. * @param options Configuration options including TTL, fetch options, and cache key generation. * @returns State object with data, error, status, and refetch function. */ export declare const useCachedFetch: <T = any>(url: string | undefined | null, options?: UseCachedFetchOptions) => UseCachedFetchResult<T>; export {};