package.dist._internal.index.d.mts Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of swr Show documentation
Show all versions of swr Show documentation
React Hooks library for remote data fetching
The newest version!
import react, { FC, PropsWithChildren } from 'react';
declare const FOCUS_EVENT = 0;
declare const RECONNECT_EVENT = 1;
declare const MUTATE_EVENT = 2;
declare const ERROR_REVALIDATE_EVENT = 3;
declare const events_ERROR_REVALIDATE_EVENT: typeof ERROR_REVALIDATE_EVENT;
declare const events_FOCUS_EVENT: typeof FOCUS_EVENT;
declare const events_MUTATE_EVENT: typeof MUTATE_EVENT;
declare const events_RECONNECT_EVENT: typeof RECONNECT_EVENT;
declare namespace events {
export { events_ERROR_REVALIDATE_EVENT as ERROR_REVALIDATE_EVENT, events_FOCUS_EVENT as FOCUS_EVENT, events_MUTATE_EVENT as MUTATE_EVENT, events_RECONNECT_EVENT as RECONNECT_EVENT };
}
type GlobalState = [
Record,
Record,
Record,
Record>,
ScopedMutator,
(key: string, value: any, prev: any) => void,
(key: string, callback: (current: any, prev: any) => void) => () => void
];
type FetcherResponse = Data | Promise;
type BareFetcher = (...args: any[]) => FetcherResponse;
type Fetcher = SWRKey extends () => infer Arg | null | undefined | false ? (arg: Arg) => FetcherResponse : SWRKey extends null | undefined | false ? never : SWRKey extends infer Arg ? (arg: Arg) => FetcherResponse : never;
type ReactUsePromise = Promise & {
status?: 'pending' | 'fulfilled' | 'rejected';
value?: T;
reason?: Error;
};
type BlockingData> = Options extends undefined ? false : Options extends {
suspense: true;
} ? true : Options extends {
fallbackData: Data;
} ? true : false;
interface InternalConfiguration {
cache: Cache;
mutate: ScopedMutator;
}
/**
* @link https://swr.vercel.app/docs/options
*/
interface PublicConfiguration {
/**
* error retry interval in milliseconds
* @defaultValue 5000
*/
errorRetryInterval: number;
/** max error retry count */
errorRetryCount?: number;
/**
* timeout to trigger the onLoadingSlow event in milliseconds
* @defaultValue 3000
*/
loadingTimeout: number;
/**
* only revalidate once during a time span in milliseconds
* @defaultValue 5000
*/
focusThrottleInterval: number;
/**
* dedupe requests with the same key in this time span in milliseconds
* @defaultValue 2000
*/
dedupingInterval: number;
/**
* @link https://swr.vercel.app/docs/revalidation
* * Disabled by default: `refreshInterval = 0`
* * If set to a number, polling interval in milliseconds
* * If set to a function, the function will receive the latest data and should return the interval in milliseconds
*/
refreshInterval?: number | ((latestData: Data | undefined) => number);
/**
* polling when the window is invisible (if `refreshInterval` is enabled)
* @defaultValue false
*
*/
refreshWhenHidden?: boolean;
/**
* polling when the browser is offline (determined by `navigator.onLine`)
*/
refreshWhenOffline?: boolean;
/**
* automatically revalidate when window gets focused
* @defaultValue true
* @link https://swr.vercel.app/docs/revalidation
*/
revalidateOnFocus: boolean;
/**
* automatically revalidate when the browser regains a network connection (via `navigator.onLine`)
* @defaultValue true
* @link https://swr.vercel.app/docs/revalidation
*/
revalidateOnReconnect: boolean;
/**
* enable or disable automatic revalidation when component is mounted
*/
revalidateOnMount?: boolean;
/**
* automatically revalidate even if there is stale data
* @defaultValue true
* @link https://swr.vercel.app/docs/revalidation#disable-automatic-revalidations
*/
revalidateIfStale: boolean;
/**
* retry when fetcher has an error
* @defaultValue true
*/
shouldRetryOnError: boolean | ((err: Error) => boolean);
/**
* keep the previous result when key is changed but data is not ready
* @defaultValue false
*/
keepPreviousData?: boolean;
/**
* @experimental enable React Suspense mode
* @defaultValue false
* @link https://swr.vercel.app/docs/suspense
*/
suspense?: boolean;
/**
* initial data to be returned (note: ***This is per-hook***)
*/
fallbackData?: Data;
/**
* the fetcher function
*/
fetcher?: Fn;
/**
* array of middleware functions
* @link https://swr.vercel.app/docs/middleware
*/
use?: Middleware[];
/**
* a key-value object of multiple fallback data
* @link https://swr.vercel.app/docs/with-nextjs#pre-rendering-with-default-data
*/
fallback: {
[key: string]: any;
};
/**
* function to detect whether pause revalidations, will ignore fetched data and errors when it returns true. Returns false by default.
*/
isPaused: () => boolean;
/**
* callback function when a request takes too long to load (see `loadingTimeout`)
*/
onLoadingSlow: (key: string, config: Readonly>) => void;
/**
* callback function when a request finishes successfully
*/
onSuccess: (data: Data, key: string, config: Readonly>) => void;
/**
* callback function when a request returns an error
*/
onError: (err: Error, key: string, config: Readonly>) => void;
/**
* handler for error retry
*/
onErrorRetry: (err: Error, key: string, config: Readonly>, revalidate: Revalidator, revalidateOpts: Required) => void;
/**
* callback function when a request is ignored
*/
onDiscarded: (key: string) => void;
/**
* comparison function used to detect when returned data has changed, to avoid spurious rerenders. By default, [stable-hash](https://github.com/shuding/stable-hash) is used.
*/
compare: (a: Data | undefined, b: Data | undefined) => boolean;
/**
* isOnline and isVisible are functions that return a boolean, to determine if the application is "active". By default, SWR will bail out a revalidation if these conditions are not met.
* @link https://swr.vercel.app/docs/advanced/react-native#customize-focus-and-reconnect-events
*/
isOnline: () => boolean;
/**
* isOnline and isVisible are functions that return a boolean, to determine if the application is "active". By default, SWR will bail out a revalidation if these conditions are not met.
* @link https://swr.vercel.app/docs/advanced/react-native#customize-focus-and-reconnect-events
*/
isVisible: () => boolean;
}
type FullConfiguration = InternalConfiguration & PublicConfiguration;
type ProviderConfiguration = {
initFocus: (callback: () => void) => (() => void) | void;
initReconnect: (callback: () => void) => (() => void) | void;
};
/**
* @example
* ```ts
* const { data, error } = useSWR(key, fetcher)
* ```
*/
interface SWRHook {
(key: SWRKey): SWRResponse;
(key: SWRKey, fetcher: Fetcher | null): SWRResponse;
(key: SWRKey, fetcher: Fetcher | null): SWRResponse;
> | undefined = SWRConfiguration> | undefined>(key: SWRKey, config: SWROptions): SWRResponse;
> | undefined = SWRConfiguration> | undefined>(key: SWRKey, fetcher: Fetcher | null, config: SWROptions): SWRResponse;
(key: Key): SWRResponse;
> | undefined = SWRConfiguration> | undefined>(key: Key, config: SWROptions): SWRResponse;
> | undefined = SWRConfiguration> | undefined>(key: Key, fetcher: BareFetcher | null, config: SWROptions): SWRResponse;
}
type Middleware = (useSWRNext: SWRHook) => (key: Key, fetcher: BareFetcher | null, config: SWRConfiguration>) => SWRResponse;
type ArgumentsTuple = readonly [any, ...unknown[]];
type Arguments = string | ArgumentsTuple | Record | null | undefined | false;
type Key = Arguments | (() => Arguments);
type StrictTupleKey = ArgumentsTuple | null | undefined | false;
type StrictKey = StrictTupleKey | (() => StrictTupleKey);
type MutatorCallback = (currentData?: Data) => Promise | undefined | Data;
/**
* @typeParam Data - The type of the data related to the key
* @typeParam MutationData - The type of the data returned by the mutator
*/
type MutatorOptions = {
revalidate?: boolean | ((data: Data, key: Arguments) => boolean);
populateCache?: boolean | ((result: MutationData, currentData: Data | undefined) => Data);
optimisticData?: Data | ((currentData: Data | undefined, displayedData: Data | undefined) => Data);
rollbackOnError?: boolean | ((error: unknown) => boolean);
throwOnError?: boolean;
};
type MutatorConfig = {
revalidate?: boolean;
populateCache?: boolean;
};
type Broadcaster = (cache: Cache, key: string, data: Data, error?: Error, isValidating?: boolean, revalidate?: boolean, populateCache?: boolean) => Promise;
type State = {
data?: Data;
error?: Error;
isValidating?: boolean;
isLoading?: boolean;
};
type MutatorFn = (cache: Cache, key: Key, data?: Data | Promise | MutatorCallback, opts?: boolean | MutatorOptions) => Promise;
type MutatorWrapper = Fn extends (...args: [...infer Parameters]) => infer Result ? Parameters[3] extends boolean ? Result : Parameters[3] extends Required> ? Parameters[3]['populateCache'] extends false ? never : Result : Result : never;
type Mutator = MutatorWrapper>;
interface ScopedMutator {
/**
* @typeParam Data - The type of the data related to the key
* @typeParam MutationData - The type of the data returned by the mutator
*/
(matcher: (key?: Arguments) => boolean, data?: MutationData | Promise | MutatorCallback, opts?: boolean | MutatorOptions): Promise>;
/**
* @typeParam Data - The type of the data related to the key
* @typeParam MutationData - The type of the data returned by the mutator
*/
(key: Arguments, data?: T | Promise | MutatorCallback, opts?: boolean | MutatorOptions): Promise;
}
/**
* @typeParam Data - The type of the data related to the key
* @typeParam MutationData - The type of the data returned by the mutator
*/
type KeyedMutator = (data?: Data | Promise | MutatorCallback, opts?: boolean | MutatorOptions) => Promise;
type SWRConfiguration = BareFetcher> = Partial> & Partial & {
provider?: (cache: Readonly) => Cache;
};
type IsLoadingResponse> = Options extends {
suspense: true;
} ? false : boolean;
type SWROptions = SWRConfiguration>;
interface SWRResponse {
/**
* The returned data of the fetcher function.
*/
data: BlockingData extends true ? Data : Data | undefined;
/**
* The error object thrown by the fetcher function.
*/
error: Error | undefined;
mutate: KeyedMutator;
isValidating: boolean;
isLoading: IsLoadingResponse;
}
type KeyLoader = ((index: number, previousPageData: any | null) => Args) | null;
interface RevalidatorOptions {
retryCount?: number;
dedupe?: boolean;
}
type Revalidator = (revalidateOpts?: RevalidatorOptions) => Promise | void;
type RevalidateEvent = typeof FOCUS_EVENT | typeof RECONNECT_EVENT | typeof MUTATE_EVENT | typeof ERROR_REVALIDATE_EVENT;
type RevalidateCallbackReturnType = {
[FOCUS_EVENT]: void;
[RECONNECT_EVENT]: void;
[MUTATE_EVENT]: Promise;
[ERROR_REVALIDATE_EVENT]: void;
};
type RevalidateCallback = (type: K, opts?: any) => RevalidateCallbackReturnType[K];
interface Cache {
keys(): IterableIterator;
get(key: string): State | undefined;
set(key: string, value: State): void;
delete(key: string): void;
}
interface StateDependencies {
data?: boolean;
error?: boolean;
isValidating?: boolean;
isLoading?: boolean;
}
declare const SWRConfig: FC SWRConfiguration);
}>>;
declare const INFINITE_PREFIX = "$inf$";
declare const initCache: (provider: Cache, options?: Partial) => [Cache, ScopedMutator, () => void, () => void] | [Cache, ScopedMutator] | undefined;
declare const compare: (currentData: any, newData: any) => boolean;
declare const cache: Cache;
declare const mutate: ScopedMutator;
declare const defaultConfig: FullConfiguration;
declare const IS_REACT_LEGACY = false;
declare const IS_SERVER: boolean;
declare const rAF: (f: (...args: any[]) => void) => number | ReturnType;
declare const useIsomorphicLayoutEffect: typeof react.useEffect;
declare const slowConnection: boolean | undefined;
declare const SWRGlobalState: WeakMap, GlobalState>;
declare const stableHash: (arg: any) => string;
declare const isWindowDefined: boolean;
declare const isDocumentDefined: boolean;
declare const hasRequestAnimationFrame: () => boolean;
declare const createCacheHelper: >(cache: Cache, key: string | undefined) => readonly [() => T, (info: T) => void, (key: string, callback: (current: any, prev: any) => void) => () => void, () => any];
declare const noop: () => void;
declare const UNDEFINED: undefined;
declare const OBJECT: ObjectConstructor;
declare const isUndefined: (v: any) => v is undefined;
declare const isFunction: any = (...args: any[]) => any>(v: unknown) => v is T;
declare const mergeObjects: (a: any, b?: any) => any;
declare const isPromiseLike: (x: unknown) => x is PromiseLike;
declare const mergeConfigs: (a: Partial, b?: Partial) => Partial;
type KeyFilter = (key?: Arguments) => boolean;
declare function internalMutate(cache: Cache, _key: KeyFilter, _data?: Data | Promise | MutatorCallback, _opts?: boolean | MutatorOptions): Promise>;
declare function internalMutate(cache: Cache, _key: Arguments, _data?: Data | Promise | MutatorCallback, _opts?: boolean | MutatorOptions): Promise;
declare const normalize: (args: [KeyType_1] | [KeyType_1, Fetcher | null] | [KeyType_1, SWRConfiguration | undefined] | [KeyType_1, Fetcher | null, SWRConfiguration | undefined]) => [KeyType_1, Fetcher | null, Partial>];
declare const withArgs: (hook: any) => SWRType;
declare const serialize: (key: Key) => [string, Arguments];
type Callback = (...args: any[]) => any;
declare const subscribeCallback: (key: string, callbacks: Record, callback: Callback) => () => void;
declare const getTimestamp: () => number;
declare const useSWRConfig: () => FullConfiguration;
declare const preset: {
readonly isOnline: () => boolean;
readonly isVisible: () => boolean;
};
declare const defaultConfigOptions: ProviderConfiguration;
declare const withMiddleware: (useSWR: SWRHook, middleware: Middleware) => SWRHook;
type PreloadFetcher = SWRKey extends () => infer Arg ? (arg: Arg) => FetcherResponse : SWRKey extends infer Arg ? (arg: Arg) => FetcherResponse : never;
declare const preload: >(key_: SWRKey, fetcher: Fetcher) => ReturnType;
export { type Arguments, type BareFetcher, type BlockingData, type Broadcaster, type Cache, type Fetcher, type FetcherResponse, type FullConfiguration, type GlobalState, INFINITE_PREFIX, IS_REACT_LEGACY, IS_SERVER, type InternalConfiguration, type IsLoadingResponse, type Key, type KeyLoader, type KeyedMutator, type Middleware, type Mutator, type MutatorCallback, type MutatorConfig, type MutatorFn, type MutatorOptions, type MutatorWrapper, OBJECT, type ProviderConfiguration, type PublicConfiguration, type ReactUsePromise, type RevalidateCallback, type RevalidateEvent, type Revalidator, type RevalidatorOptions, SWRConfig, type SWRConfiguration, SWRGlobalState, type SWRHook, type SWRResponse, type ScopedMutator, type State, type StateDependencies, type StrictTupleKey, UNDEFINED, cache, compare, createCacheHelper, defaultConfig, defaultConfigOptions, getTimestamp, hasRequestAnimationFrame, initCache, internalMutate, isDocumentDefined, isFunction, isPromiseLike, isUndefined, isWindowDefined, mergeConfigs, mergeObjects, mutate, noop, normalize, preload, preset, rAF, events as revalidateEvents, serialize, slowConnection, stableHash, subscribeCallback, useIsomorphicLayoutEffect, useSWRConfig, withArgs, withMiddleware };