Debian Codegraph @

install/freeipa-webui/node_modules/@reduxjs/toolkit/dist/query/index.d.ts

raw
1 import * as _reduxjs_toolkit from '@reduxjs/toolkit';
2 import { ThunkDispatch, UnknownAction, AsyncThunk, ThunkAction, SHOULD_AUTOBATCH, Draft, SafePromise, SerializedError, PayloadAction, ActionCreatorWithoutPayload, Reducer, Middleware, ActionCreatorWithPayload, createSelector } from '@reduxjs/toolkit';
3 import { Patch } from 'immer';
4 import * as redux from 'redux';
5
6 type Id<T> = {
7 [K in keyof T]: T[K];
8 } & {};
9 type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
10 type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;
11 /**
12 * Convert a Union type `(A|B)` to an intersection type `(A&B)`
13 */
14 type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
15 type NonOptionalKeys<T> = {
16 [K in keyof T]-?: undefined extends T[K] ? never : K;
17 }[keyof T];
18 type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;
19 type NoInfer<T> = [T][T extends any ? 0 : never];
20 type NonUndefined<T> = T extends undefined ? never : T;
21 type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;
22 type MaybePromise<T> = T | PromiseLike<T>;
23 type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;
24 type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;
25 type CastAny<T, CastTo> = IsAny<T, CastTo, T>;
26
27 interface BaseQueryApi {
28 signal: AbortSignal;
29 abort: (reason?: string) => void;
30 dispatch: ThunkDispatch<any, any, any>;
31 getState: () => unknown;
32 extra: unknown;
33 endpoint: string;
34 type: 'query' | 'mutation';
35 /**
36 * Only available for queries: indicates if a query has been forced,
37 * i.e. it would have been fetched even if there would already be a cache entry
38 * (this does not mean that there is already a cache entry though!)
39 *
40 * This can be used to for example add a `Cache-Control: no-cache` header for
41 * invalidated queries.
42 */
43 forced?: boolean;
44 /**
45 * Only available for queries: the cache key that was used to store the query result
46 */
47 queryCacheKey?: string;
48 }
49 type QueryReturnValue<T = unknown, E = unknown, M = unknown> = {
50 error: E;
51 data?: undefined;
52 meta?: M;
53 } | {
54 error?: undefined;
55 data: T;
56 meta?: M;
57 };
58 type BaseQueryFn<Args = any, Result = unknown, Error = unknown, DefinitionExtraOptions = {}, Meta = {}> = (args: Args, api: BaseQueryApi, extraOptions: DefinitionExtraOptions) => MaybePromise<QueryReturnValue<Result, Error, Meta>>;
59 type BaseQueryEnhancer<AdditionalArgs = unknown, AdditionalDefinitionExtraOptions = unknown, Config = void> = <BaseQuery extends BaseQueryFn>(baseQuery: BaseQuery, config: Config) => BaseQueryFn<BaseQueryArg<BaseQuery> & AdditionalArgs, BaseQueryResult<BaseQuery>, BaseQueryError<BaseQuery>, BaseQueryExtraOptions<BaseQuery> & AdditionalDefinitionExtraOptions, NonNullable<BaseQueryMeta<BaseQuery>>>;
60 /**
61 * @public
62 */
63 type BaseQueryResult<BaseQuery extends BaseQueryFn> = UnwrapPromise<ReturnType<BaseQuery>> extends infer Unwrapped ? Unwrapped extends {
64 data: any;
65 } ? Unwrapped['data'] : never : never;
66 /**
67 * @public
68 */
69 type BaseQueryMeta<BaseQuery extends BaseQueryFn> = UnwrapPromise<ReturnType<BaseQuery>>['meta'];
70 /**
71 * @public
72 */
73 type BaseQueryError<BaseQuery extends BaseQueryFn> = Exclude<UnwrapPromise<ReturnType<BaseQuery>>, {
74 error?: undefined;
75 }>['error'];
76 /**
77 * @public
78 */
79 type BaseQueryArg<T extends (arg: any, ...args: any[]) => any> = T extends (arg: infer A, ...args: any[]) => any ? A : any;
80 /**
81 * @public
82 */
83 type BaseQueryExtraOptions<BaseQuery extends BaseQueryFn> = Parameters<BaseQuery>[2];
84
85 declare const defaultSerializeQueryArgs: SerializeQueryArgs<any>;
86 type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {
87 queryArgs: QueryArgs;
88 endpointDefinition: EndpointDefinition<any, any, any, any>;
89 endpointName: string;
90 }) => ReturnType;
91 type InternalSerializeQueryArgs = (_: {
92 queryArgs: any;
93 endpointDefinition: EndpointDefinition<any, any, any, any>;
94 endpointName: string;
95 }) => QueryCacheKey;
96
97 interface CreateApiOptions<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never> {
98 /**
99 * The base query used by each endpoint if no `queryFn` option is specified. RTK Query exports a utility called [fetchBaseQuery](./fetchBaseQuery) as a lightweight wrapper around `fetch` for common use-cases. See [Customizing Queries](../../rtk-query/usage/customizing-queries) if `fetchBaseQuery` does not handle your requirements.
100 *
101 * @example
102 *
103 * ```ts
104 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
105 *
106 * const api = createApi({
107 * // highlight-start
108 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
109 * // highlight-end
110 * endpoints: (build) => ({
111 * // ...endpoints
112 * }),
113 * })
114 * ```
115 */
116 baseQuery: BaseQuery;
117 /**
118 * An array of string tag type names. Specifying tag types is optional, but you should define them so that they can be used for caching and invalidation. When defining a tag type, you will be able to [provide](../../rtk-query/usage/automated-refetching#providing-tags) them with `providesTags` and [invalidate](../../rtk-query/usage/automated-refetching#invalidating-tags) them with `invalidatesTags` when configuring [endpoints](#endpoints).
119 *
120 * @example
121 *
122 * ```ts
123 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
124 *
125 * const api = createApi({
126 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
127 * // highlight-start
128 * tagTypes: ['Post', 'User'],
129 * // highlight-end
130 * endpoints: (build) => ({
131 * // ...endpoints
132 * }),
133 * })
134 * ```
135 */
136 tagTypes?: readonly TagTypes[];
137 /**
138 * The `reducerPath` is a _unique_ key that your service will be mounted to in your store. If you call `createApi` more than once in your application, you will need to provide a unique value each time. Defaults to `'api'`.
139 *
140 * @example
141 *
142 * ```ts
143 * // codeblock-meta title="apis.js"
144 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';
145 *
146 * const apiOne = createApi({
147 * // highlight-start
148 * reducerPath: 'apiOne',
149 * // highlight-end
150 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
151 * endpoints: (builder) => ({
152 * // ...endpoints
153 * }),
154 * });
155 *
156 * const apiTwo = createApi({
157 * // highlight-start
158 * reducerPath: 'apiTwo',
159 * // highlight-end
160 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
161 * endpoints: (builder) => ({
162 * // ...endpoints
163 * }),
164 * });
165 * ```
166 */
167 reducerPath?: ReducerPath;
168 /**
169 * Accepts a custom function if you have a need to change the creation of cache keys for any reason.
170 */
171 serializeQueryArgs?: SerializeQueryArgs<unknown>;
172 /**
173 * Endpoints are a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are three endpoint types: [`query`](../../rtk-query/usage/queries), [`infiniteQuery`](../../rtk-query/usage/infinite-queries) and [`mutation`](../../rtk-query/usage/mutations).
174 */
175 endpoints(build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>): Definitions;
176 /**
177 * Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.
178 *
179 * ```ts
180 * // codeblock-meta title="keepUnusedDataFor example"
181 *
182 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
183 * interface Post {
184 * id: number
185 * name: string
186 * }
187 * type PostsResponse = Post[]
188 *
189 * const api = createApi({
190 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
191 * endpoints: (build) => ({
192 * getPosts: build.query<PostsResponse, void>({
193 * query: () => 'posts',
194 * // highlight-start
195 * keepUnusedDataFor: 5
196 * // highlight-end
197 * })
198 * })
199 * })
200 * ```
201 */
202 keepUnusedDataFor?: number;
203 /**
204 * Defaults to `false`. This setting allows you to control whether if a cached result is already available RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.
205 * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
206 * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.
207 * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.
208 *
209 * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
210 */
211 refetchOnMountOrArgChange?: boolean | number;
212 /**
213 * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.
214 *
215 * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
216 *
217 * Note: requires [`setupListeners`](./setupListeners) to have been called.
218 */
219 refetchOnFocus?: boolean;
220 /**
221 * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.
222 *
223 * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
224 *
225 * Note: requires [`setupListeners`](./setupListeners) to have been called.
226 */
227 refetchOnReconnect?: boolean;
228 /**
229 * Defaults to `'delayed'`. This setting allows you to control when tags are invalidated after a mutation.
230 *
231 * - `'immediately'`: Queries are invalidated instantly after the mutation finished, even if they are running.
232 * If the query provides tags that were invalidated while it ran, it won't be re-fetched.
233 * - `'delayed'`: Invalidation only happens after all queries and mutations are settled.
234 * This ensures that queries are always invalidated correctly and automatically "batches" invalidations of concurrent mutations.
235 * Note that if you constantly have some queries (or mutations) running, this can delay tag invalidations indefinitely.
236 */
237 invalidationBehavior?: 'delayed' | 'immediately';
238 /**
239 * A function that is passed every dispatched action. If this returns something other than `undefined`,
240 * that return value will be used to rehydrate fulfilled & errored queries.
241 *
242 * @example
243 *
244 * ```ts
245 * // codeblock-meta title="next-redux-wrapper rehydration example"
246 * import type { Action, PayloadAction } from '@reduxjs/toolkit'
247 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
248 * import { HYDRATE } from 'next-redux-wrapper'
249 *
250 * type RootState = any; // normally inferred from state
251 *
252 * function isHydrateAction(action: Action): action is PayloadAction<RootState> {
253 * return action.type === HYDRATE
254 * }
255 *
256 * export const api = createApi({
257 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
258 * // highlight-start
259 * extractRehydrationInfo(action, { reducerPath }): any {
260 * if (isHydrateAction(action)) {
261 * return action.payload[reducerPath]
262 * }
263 * },
264 * // highlight-end
265 * endpoints: (build) => ({
266 * // omitted
267 * }),
268 * })
269 * ```
270 */
271 extractRehydrationInfo?: (action: UnknownAction, { reducerPath, }: {
272 reducerPath: ReducerPath;
273 }) => undefined | CombinedState<NoInfer<Definitions>, NoInfer<TagTypes>, NoInfer<ReducerPath>>;
274 }
275 type CreateApi<Modules extends ModuleName> = {
276 /**
277 * Creates a service to use in your application. Contains only the basic redux logic (the core module).
278 *
279 * @link https://rtk-query-docs.netlify.app/api/createApi
280 */
281 <BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never>(options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>;
282 };
283 /**
284 * Builds a `createApi` method based on the provided `modules`.
285 *
286 * @link https://rtk-query-docs.netlify.app/concepts/customizing-create-api
287 *
288 * @example
289 * ```ts
290 * const MyContext = React.createContext<ReactReduxContextValue | null>(null);
291 * const customCreateApi = buildCreateApi(
292 * coreModule(),
293 * reactHooksModule({
294 * hooks: {
295 * useDispatch: createDispatchHook(MyContext),
296 * useSelector: createSelectorHook(MyContext),
297 * useStore: createStoreHook(MyContext)
298 * }
299 * })
300 * );
301 * ```
302 *
303 * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints
304 * @returns A `createApi` method using the provided `modules`.
305 */
306 declare function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(...modules: Modules): CreateApi<Modules[number]['name']>;
307
308 type BuildThunksApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = Matchers<QueryThunk, Definition>;
309 type BuildThunksApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = Matchers<InfiniteQueryThunk<any>, Definition>;
310 type BuildThunksApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = Matchers<MutationThunk, Definition>;
311 type EndpointThunk<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = Definition extends EndpointDefinition<infer QueryArg, infer BaseQueryFn, any, infer ResultType> ? Thunk extends AsyncThunk<unknown, infer ATArg, infer ATConfig> ? AsyncThunk<ResultType, ATArg & {
312 originalArgs: QueryArg;
313 }, ATConfig & {
314 rejectValue: BaseQueryError<BaseQueryFn>;
315 }> : never : Definition extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQueryFn, any, infer ResultType> ? Thunk extends AsyncThunk<unknown, infer ATArg, infer ATConfig> ? AsyncThunk<InfiniteData<ResultType, PageParam>, ATArg & {
316 originalArgs: QueryArg;
317 }, ATConfig & {
318 rejectValue: BaseQueryError<BaseQueryFn>;
319 }> : never : never;
320 type PendingAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>;
321 type FulfilledAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>;
322 type RejectedAction<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>;
323 type Matcher<M> = (value: any) => value is M;
324 interface Matchers<Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>, Definition extends EndpointDefinition<any, any, any, any>> {
325 matchPending: Matcher<PendingAction<Thunk, Definition>>;
326 matchFulfilled: Matcher<FulfilledAction<Thunk, Definition>>;
327 matchRejected: Matcher<RejectedAction<Thunk, Definition>>;
328 }
329 type QueryThunkArg = QuerySubstateIdentifier & StartQueryActionCreatorOptions & {
330 type: 'query';
331 originalArgs: unknown;
332 endpointName: string;
333 };
334 type InfiniteQueryThunkArg<D extends InfiniteQueryDefinition<any, any, any, any, any>> = QuerySubstateIdentifier & StartInfiniteQueryActionCreatorOptions<D> & {
335 type: `query`;
336 originalArgs: unknown;
337 endpointName: string;
338 param: unknown;
339 direction?: InfiniteQueryDirection;
340 };
341 type MutationThunkArg = {
342 type: 'mutation';
343 originalArgs: unknown;
344 endpointName: string;
345 track?: boolean;
346 fixedCacheKey?: string;
347 };
348 type ThunkResult = unknown;
349 type ThunkApiMetaConfig = {
350 pendingMeta: {
351 startedTimeStamp: number;
352 [SHOULD_AUTOBATCH]: true;
353 };
354 fulfilledMeta: {
355 fulfilledTimeStamp: number;
356 baseQueryMeta: unknown;
357 [SHOULD_AUTOBATCH]: true;
358 };
359 rejectedMeta: {
360 baseQueryMeta: unknown;
361 [SHOULD_AUTOBATCH]: true;
362 };
363 };
364 type QueryThunk = AsyncThunk<ThunkResult, QueryThunkArg, ThunkApiMetaConfig>;
365 type InfiniteQueryThunk<D extends InfiniteQueryDefinition<any, any, any, any, any>> = AsyncThunk<ThunkResult, InfiniteQueryThunkArg<D>, ThunkApiMetaConfig>;
366 type MutationThunk = AsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig>;
367 type MaybeDrafted<T> = T | Draft<T>;
368 type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>;
369 type PatchQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, patches: readonly Patch[], updateProvided?: boolean) => ThunkAction<void, PartialState, any, UnknownAction>;
370 type AllQueryKeys<Definitions extends EndpointDefinitions> = QueryKeys<Definitions> | InfiniteQueryKeys<Definitions>;
371 type QueryArgFromAnyQueryDefinition<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryArgFrom<Definitions[EndpointName]> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? QueryArgFrom<Definitions[EndpointName]> : never;
372 type DataFromAnyQueryDefinition<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteData<ResultTypeFrom<Definitions[EndpointName]>, PageParamFrom<Definitions[EndpointName]>> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? ResultTypeFrom<Definitions[EndpointName]> : unknown;
373 type UpsertThunkResult<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryActionCreatorResult<Definitions[EndpointName]> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? QueryActionCreatorResult<Definitions[EndpointName]> : QueryActionCreatorResult<never>;
374 type UpdateQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>, updateRecipe: Recipe<DataFromAnyQueryDefinition<Definitions, EndpointName>>, updateProvided?: boolean) => ThunkAction<PatchCollection, PartialState, any, UnknownAction>;
375 type UpsertQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>, value: DataFromAnyQueryDefinition<Definitions, EndpointName>) => ThunkAction<UpsertThunkResult<Definitions, EndpointName>, PartialState, any, UnknownAction>;
376 /**
377 * An object returned from dispatching a `api.util.updateQueryData` call.
378 */
379 type PatchCollection = {
380 /**
381 * An `immer` Patch describing the cache update.
382 */
383 patches: Patch[];
384 /**
385 * An `immer` Patch to revert the cache update.
386 */
387 inversePatches: Patch[];
388 /**
389 * A function that will undo the cache update.
390 */
391 undo: () => void;
392 };
393
394 type SkipToken = typeof skipToken;
395 /**
396 * Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`
397 * instead of the query argument to get the same effect as if setting
398 * `skip: true` in the query options.
399 *
400 * Useful for scenarios where a query should be skipped when `arg` is `undefined`
401 * and TypeScript complains about it because `arg` is not allowed to be passed
402 * in as `undefined`, such as
403 *
404 * ```ts
405 * // codeblock-meta title="will error if the query argument is not allowed to be undefined" no-transpile
406 * useSomeQuery(arg, { skip: !!arg })
407 * ```
408 *
409 * ```ts
410 * // codeblock-meta title="using skipToken instead" no-transpile
411 * useSomeQuery(arg ?? skipToken)
412 * ```
413 *
414 * If passed directly into a query or mutation selector, that selector will always
415 * return an uninitialized state.
416 */
417 export declare const skipToken: unique symbol;
418 type BuildSelectorsApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {
419 select: QueryResultSelectorFactory<Definition, RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;
420 };
421 type BuildSelectorsApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {
422 select: InfiniteQueryResultSelectorFactory<Definition, RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;
423 };
424 type BuildSelectorsApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {
425 select: MutationResultSelectorFactory<Definition, RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;
426 };
427 type QueryResultSelectorFactory<Definition extends QueryDefinition<any, any, any, any>, RootState> = (queryArg: QueryArgFrom<Definition> | SkipToken) => (state: RootState) => QueryResultSelectorResult<Definition>;
428 type QueryResultSelectorResult<Definition extends QueryDefinition<any, any, any, any>> = QuerySubState<Definition> & RequestStatusFlags;
429 type InfiniteQueryResultSelectorFactory<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, RootState> = (queryArg: InfiniteQueryArgFrom<Definition> | SkipToken) => (state: RootState) => InfiniteQueryResultSelectorResult<Definition>;
430 type InfiniteQueryResultFlags = {
431 hasNextPage: boolean;
432 hasPreviousPage: boolean;
433 isFetchingNextPage: boolean;
434 isFetchingPreviousPage: boolean;
435 isFetchNextPageError: boolean;
436 isFetchPreviousPageError: boolean;
437 };
438 type InfiniteQueryResultSelectorResult<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = InfiniteQuerySubState<Definition> & RequestStatusFlags & InfiniteQueryResultFlags;
439 type MutationResultSelectorFactory<Definition extends MutationDefinition<any, any, any, any>, RootState> = (requestId: string | {
440 requestId: string | undefined;
441 fixedCacheKey: string | undefined;
442 } | SkipToken) => (state: RootState) => MutationResultSelectorResult<Definition>;
443 type MutationResultSelectorResult<Definition extends MutationDefinition<any, any, any, any>> = MutationSubState<Definition> & RequestStatusFlags;
444
445 type BuildInitiateApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = {
446 initiate: StartQueryActionCreator<Definition>;
447 };
448 type BuildInitiateApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {
449 initiate: StartInfiniteQueryActionCreator<Definition>;
450 };
451 type BuildInitiateApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = {
452 initiate: StartMutationActionCreator<Definition>;
453 };
454 declare const forceQueryFnSymbol: unique symbol;
455 type StartQueryActionCreatorOptions = {
456 subscribe?: boolean;
457 forceRefetch?: boolean | number;
458 subscriptionOptions?: SubscriptionOptions;
459 [forceQueryFnSymbol]?: () => QueryReturnValue;
460 };
461 type StartInfiniteQueryActionCreatorOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>> = StartQueryActionCreatorOptions & {
462 direction?: InfiniteQueryDirection;
463 param?: unknown;
464 } & Partial<Pick<Partial<InfiniteQueryConfigOptions<ResultTypeFrom<D>, PageParamFrom<D>>>, 'initialPageParam'>>;
465 type StartQueryActionCreator<D extends QueryDefinition<any, any, any, any, any>> = (arg: QueryArgFrom<D>, options?: StartQueryActionCreatorOptions) => ThunkAction<QueryActionCreatorResult<D>, any, any, UnknownAction>;
466 type StartInfiniteQueryActionCreator<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D>, options?: StartInfiniteQueryActionCreatorOptions<D>) => ThunkAction<InfiniteQueryActionCreatorResult<D>, any, any, UnknownAction>;
467 type QueryActionCreatorFields = {
468 requestId: string;
469 subscriptionOptions: SubscriptionOptions | undefined;
470 abort(): void;
471 unsubscribe(): void;
472 updateSubscriptionOptions(options: SubscriptionOptions): void;
473 queryCacheKey: string;
474 };
475 type QueryActionCreatorResult<D extends QueryDefinition<any, any, any, any>> = SafePromise<QueryResultSelectorResult<D>> & QueryActionCreatorFields & {
476 arg: QueryArgFrom<D>;
477 unwrap(): Promise<ResultTypeFrom<D>>;
478 refetch(): QueryActionCreatorResult<D>;
479 };
480 type InfiniteQueryActionCreatorResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = SafePromise<InfiniteQueryResultSelectorResult<D>> & QueryActionCreatorFields & {
481 arg: InfiniteQueryArgFrom<D>;
482 unwrap(): Promise<InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>>;
483 refetch(): InfiniteQueryActionCreatorResult<D>;
484 };
485 type StartMutationActionCreator<D extends MutationDefinition<any, any, any, any>> = (arg: QueryArgFrom<D>, options?: {
486 /**
487 * If this mutation should be tracked in the store.
488 * If you just want to manually trigger this mutation using `dispatch` and don't care about the
489 * result, state & potential errors being held in store, you can set this to false.
490 * (defaults to `true`)
491 */
492 track?: boolean;
493 fixedCacheKey?: string;
494 }) => ThunkAction<MutationActionCreatorResult<D>, any, any, UnknownAction>;
495 type MutationActionCreatorResult<D extends MutationDefinition<any, any, any, any>> = SafePromise<{
496 data: ResultTypeFrom<D>;
497 error?: undefined;
498 } | {
499 data?: undefined;
500 error: Exclude<BaseQueryError<D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQuery : never>, undefined> | SerializedError;
501 }> & {
502 /** @internal */
503 arg: {
504 /**
505 * The name of the given endpoint for the mutation
506 */
507 endpointName: string;
508 /**
509 * The original arguments supplied to the mutation call
510 */
511 originalArgs: QueryArgFrom<D>;
512 /**
513 * Whether the mutation is being tracked in the store.
514 */
515 track?: boolean;
516 fixedCacheKey?: string;
517 };
518 /**
519 * A unique string generated for the request sequence
520 */
521 requestId: string;
522 /**
523 * A method to cancel the mutation promise. Note that this is not intended to prevent the mutation
524 * that was fired off from reaching the server, but only to assist in handling the response.
525 *
526 * Calling `abort()` prior to the promise resolving will force it to reach the error state with
527 * the serialized error:
528 * `{ name: 'AbortError', message: 'Aborted' }`
529 *
530 * @example
531 * ```ts
532 * const [updateUser] = useUpdateUserMutation();
533 *
534 * useEffect(() => {
535 * const promise = updateUser(id);
536 * promise
537 * .unwrap()
538 * .catch((err) => {
539 * if (err.name === 'AbortError') return;
540 * // else handle the unexpected error
541 * })
542 *
543 * return () => {
544 * promise.abort();
545 * }
546 * }, [id, updateUser])
547 * ```
548 */
549 abort(): void;
550 /**
551 * Unwraps a mutation call to provide the raw response/error.
552 *
553 * @remarks
554 * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
555 *
556 * @example
557 * ```ts
558 * // codeblock-meta title="Using .unwrap"
559 * addPost({ id: 1, name: 'Example' })
560 * .unwrap()
561 * .then((payload) => console.log('fulfilled', payload))
562 * .catch((error) => console.error('rejected', error));
563 * ```
564 *
565 * @example
566 * ```ts
567 * // codeblock-meta title="Using .unwrap with async await"
568 * try {
569 * const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
570 * console.log('fulfilled', payload)
571 * } catch (error) {
572 * console.error('rejected', error);
573 * }
574 * ```
575 */
576 unwrap(): Promise<ResultTypeFrom<D>>;
577 /**
578 * A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.
579 The value returned by the hook will reset to `isUninitialized` afterwards.
580 */
581 reset(): void;
582 };
583
584 type ReferenceCacheLifecycle = never;
585 interface QueryBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends LifecycleApi<ReducerPath> {
586 /**
587 * Gets the current value of this cache entry.
588 */
589 getCacheEntry(): QueryResultSelectorResult<{
590 type: DefinitionType.query;
591 } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType>>;
592 /**
593 * Updates the current cache entry value.
594 * For documentation see `api.util.updateQueryData`.
595 */
596 updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection;
597 }
598 type MutationBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = LifecycleApi<ReducerPath> & {
599 /**
600 * Gets the current value of this cache entry.
601 */
602 getCacheEntry(): MutationResultSelectorResult<{
603 type: DefinitionType.mutation;
604 } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType>>;
605 };
606 type LifecycleApi<ReducerPath extends string = string> = {
607 /**
608 * The dispatch method for the store
609 */
610 dispatch: ThunkDispatch<any, any, UnknownAction>;
611 /**
612 * A method to get the current state
613 */
614 getState(): RootState<any, any, ReducerPath>;
615 /**
616 * `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.
617 */
618 extra: unknown;
619 /**
620 * A unique ID generated for the mutation
621 */
622 requestId: string;
623 };
624 type CacheLifecyclePromises<ResultType = unknown, MetaType = unknown> = {
625 /**
626 * Promise that will resolve with the first value for this cache key.
627 * This allows you to `await` until an actual value is in cache.
628 *
629 * If the cache entry is removed from the cache before any value has ever
630 * been resolved, this Promise will reject with
631 * `new Error('Promise never resolved before cacheEntryRemoved.')`
632 * to prevent memory leaks.
633 * You can just re-throw that error (or not handle it at all) -
634 * it will be caught outside of `cacheEntryAdded`.
635 *
636 * If you don't interact with this promise, it will not throw.
637 */
638 cacheDataLoaded: PromiseWithKnownReason<{
639 /**
640 * The (transformed) query result.
641 */
642 data: ResultType;
643 /**
644 * The `meta` returned by the `baseQuery`
645 */
646 meta: MetaType;
647 }, typeof neverResolvedError>;
648 /**
649 * Promise that allows you to wait for the point in time when the cache entry
650 * has been removed from the cache, by not being used/subscribed to any more
651 * in the application for too long or by dispatching `api.util.resetApiState`.
652 */
653 cacheEntryRemoved: Promise<void>;
654 };
655 interface QueryCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {
656 }
657 type MutationCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>>;
658 type CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {
659 onCacheEntryAdded?(arg: QueryArg, api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
660 };
661 type CacheLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;
662 type CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {
663 onCacheEntryAdded?(arg: QueryArg, api: MutationCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
664 };
665 declare const neverResolvedError: Error & {
666 message: "Promise never resolved before cacheEntryRemoved.";
667 };
668
669 type ReferenceQueryLifecycle = never;
670 type QueryLifecyclePromises<ResultType, BaseQuery extends BaseQueryFn> = {
671 /**
672 * Promise that will resolve with the (transformed) query result.
673 *
674 * If the query fails, this promise will reject with the error.
675 *
676 * This allows you to `await` for the query to finish.
677 *
678 * If you don't interact with this promise, it will not throw.
679 */
680 queryFulfilled: PromiseWithKnownReason<{
681 /**
682 * The (transformed) query result.
683 */
684 data: ResultType;
685 /**
686 * The `meta` returned by the `baseQuery`
687 */
688 meta: BaseQueryMeta<BaseQuery>;
689 }, QueryFulfilledRejectionReason<BaseQuery>>;
690 };
691 type QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> = {
692 error: BaseQueryError<BaseQuery>;
693 /**
694 * If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.
695 */
696 isUnhandledError: false;
697 /**
698 * The `meta` returned by the `baseQuery`
699 */
700 meta: BaseQueryMeta<BaseQuery>;
701 } | {
702 error: unknown;
703 meta?: undefined;
704 /**
705 * If this is `true`, that means that this error is the result of `baseQueryFn`, `queryFn`, `transformResponse` or `transformErrorResponse` throwing an error instead of handling it properly.
706 * There can not be made any assumption about the shape of `error`.
707 */
708 isUnhandledError: true;
709 };
710 type QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {
711 /**
712 * A function that is called when the individual query is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).
713 *
714 * Can be used to perform side-effects throughout the lifecycle of the query.
715 *
716 * @example
717 * ```ts
718 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
719 * import { messageCreated } from './notificationsSlice
720 * export interface Post {
721 * id: number
722 * name: string
723 * }
724 *
725 * const api = createApi({
726 * baseQuery: fetchBaseQuery({
727 * baseUrl: '/',
728 * }),
729 * endpoints: (build) => ({
730 * getPost: build.query<Post, number>({
731 * query: (id) => `post/${id}`,
732 * async onQueryStarted(id, { dispatch, queryFulfilled }) {
733 * // `onStart` side-effect
734 * dispatch(messageCreated('Fetching posts...'))
735 * try {
736 * const { data } = await queryFulfilled
737 * // `onSuccess` side-effect
738 * dispatch(messageCreated('Posts received!'))
739 * } catch (err) {
740 * // `onError` side-effect
741 * dispatch(messageCreated('Error fetching posts!'))
742 * }
743 * }
744 * }),
745 * }),
746 * })
747 * ```
748 */
749 onQueryStarted?(queryArgument: QueryArg, queryLifeCycleApi: QueryLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
750 };
751 type QueryLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;
752 type QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {
753 /**
754 * A function that is called when the individual mutation is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).
755 *
756 * Can be used for `optimistic updates`.
757 *
758 * @example
759 *
760 * ```ts
761 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
762 * export interface Post {
763 * id: number
764 * name: string
765 * }
766 *
767 * const api = createApi({
768 * baseQuery: fetchBaseQuery({
769 * baseUrl: '/',
770 * }),
771 * tagTypes: ['Post'],
772 * endpoints: (build) => ({
773 * getPost: build.query<Post, number>({
774 * query: (id) => `post/${id}`,
775 * providesTags: ['Post'],
776 * }),
777 * updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
778 * query: ({ id, ...patch }) => ({
779 * url: `post/${id}`,
780 * method: 'PATCH',
781 * body: patch,
782 * }),
783 * invalidatesTags: ['Post'],
784 * async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
785 * const patchResult = dispatch(
786 * api.util.updateQueryData('getPost', id, (draft) => {
787 * Object.assign(draft, patch)
788 * })
789 * )
790 * try {
791 * await queryFulfilled
792 * } catch {
793 * patchResult.undo()
794 * }
795 * },
796 * }),
797 * }),
798 * })
799 * ```
800 */
801 onQueryStarted?(queryArgument: QueryArg, mutationLifeCycleApi: MutationLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
802 };
803 interface QueryLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, QueryLifecyclePromises<ResultType, BaseQuery> {
804 }
805 type MutationLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & QueryLifecyclePromises<ResultType, BaseQuery>;
806 /**
807 * Provides a way to define a strongly-typed version of
808 * {@linkcode QueryLifecycleQueryExtraOptions.onQueryStarted | onQueryStarted}
809 * for a specific query.
810 *
811 * @example
812 * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>
813 *
814 * ```ts
815 * import type { TypedQueryOnQueryStarted } from '@reduxjs/toolkit/query'
816 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
817 *
818 * type Post = {
819 * id: number
820 * title: string
821 * userId: number
822 * }
823 *
824 * type PostsApiResponse = {
825 * posts: Post[]
826 * total: number
827 * skip: number
828 * limit: number
829 * }
830 *
831 * type QueryArgument = number | undefined
832 *
833 * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
834 *
835 * const baseApiSlice = createApi({
836 * baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),
837 * reducerPath: 'postsApi',
838 * tagTypes: ['Posts'],
839 * endpoints: (build) => ({
840 * getPosts: build.query<PostsApiResponse, void>({
841 * query: () => `/posts`,
842 * }),
843 *
844 * getPostById: build.query<Post, QueryArgument>({
845 * query: (postId) => `/posts/${postId}`,
846 * }),
847 * }),
848 * })
849 *
850 * const updatePostOnFulfilled: TypedQueryOnQueryStarted<
851 * PostsApiResponse,
852 * QueryArgument,
853 * BaseQueryFunction,
854 * 'postsApi'
855 * > = async (queryArgument, { dispatch, queryFulfilled }) => {
856 * const result = await queryFulfilled
857 *
858 * const { posts } = result.data
859 *
860 * // Pre-fill the individual post entries with the results
861 * // from the list endpoint query
862 * dispatch(
863 * baseApiSlice.util.upsertQueryEntries(
864 * posts.map((post) => ({
865 * endpointName: 'getPostById',
866 * arg: post.id,
867 * value: post,
868 * })),
869 * ),
870 * )
871 * }
872 *
873 * export const extendedApiSlice = baseApiSlice.injectEndpoints({
874 * endpoints: (build) => ({
875 * getPostsByUserId: build.query<PostsApiResponse, QueryArgument>({
876 * query: (userId) => `/posts/user/${userId}`,
877 *
878 * onQueryStarted: updatePostOnFulfilled,
879 * }),
880 * }),
881 * })
882 * ```
883 *
884 * @template ResultType - The type of the result `data` returned by the query.
885 * @template QueryArgumentType - The type of the argument passed into the query.
886 * @template BaseQueryFunctionType - The type of the base query function being used.
887 * @template ReducerPath - The type representing the `reducerPath` for the API slice.
888 *
889 * @since 2.4.0
890 * @public
891 */
892 type TypedQueryOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];
893 /**
894 * Provides a way to define a strongly-typed version of
895 * {@linkcode QueryLifecycleMutationExtraOptions.onQueryStarted | onQueryStarted}
896 * for a specific mutation.
897 *
898 * @example
899 * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>
900 *
901 * ```ts
902 * import type { TypedMutationOnQueryStarted } from '@reduxjs/toolkit/query'
903 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
904 *
905 * type Post = {
906 * id: number
907 * title: string
908 * userId: number
909 * }
910 *
911 * type PostsApiResponse = {
912 * posts: Post[]
913 * total: number
914 * skip: number
915 * limit: number
916 * }
917 *
918 * type QueryArgument = Pick<Post, 'id'> & Partial<Post>
919 *
920 * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
921 *
922 * const baseApiSlice = createApi({
923 * baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),
924 * reducerPath: 'postsApi',
925 * tagTypes: ['Posts'],
926 * endpoints: (build) => ({
927 * getPosts: build.query<PostsApiResponse, void>({
928 * query: () => `/posts`,
929 * }),
930 *
931 * getPostById: build.query<Post, number>({
932 * query: (postId) => `/posts/${postId}`,
933 * }),
934 * }),
935 * })
936 *
937 * const updatePostOnFulfilled: TypedMutationOnQueryStarted<
938 * Post,
939 * QueryArgument,
940 * BaseQueryFunction,
941 * 'postsApi'
942 * > = async ({ id, ...patch }, { dispatch, queryFulfilled }) => {
943 * const patchCollection = dispatch(
944 * baseApiSlice.util.updateQueryData('getPostById', id, (draftPost) => {
945 * Object.assign(draftPost, patch)
946 * }),
947 * )
948 *
949 * try {
950 * await queryFulfilled
951 * } catch {
952 * patchCollection.undo()
953 * }
954 * }
955 *
956 * export const extendedApiSlice = baseApiSlice.injectEndpoints({
957 * endpoints: (build) => ({
958 * addPost: build.mutation<Post, Omit<QueryArgument, 'id'>>({
959 * query: (body) => ({
960 * url: `posts/add`,
961 * method: 'POST',
962 * body,
963 * }),
964 *
965 * onQueryStarted: updatePostOnFulfilled,
966 * }),
967 *
968 * updatePost: build.mutation<Post, QueryArgument>({
969 * query: ({ id, ...patch }) => ({
970 * url: `post/${id}`,
971 * method: 'PATCH',
972 * body: patch,
973 * }),
974 *
975 * onQueryStarted: updatePostOnFulfilled,
976 * }),
977 * }),
978 * })
979 * ```
980 *
981 * @template ResultType - The type of the result `data` returned by the query.
982 * @template QueryArgumentType - The type of the argument passed into the query.
983 * @template BaseQueryFunctionType - The type of the base query function being used.
984 * @template ReducerPath - The type representing the `reducerPath` for the API slice.
985 *
986 * @since 2.4.0
987 * @public
988 */
989 type TypedMutationOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleMutationExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];
990
991 /**
992 * A typesafe single entry to be upserted into the cache
993 */
994 type NormalizedQueryUpsertEntry<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = {
995 endpointName: EndpointName;
996 arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>;
997 value: DataFromAnyQueryDefinition<Definitions, EndpointName>;
998 };
999 /**
1000 * The internal version that is not typesafe since we can't carry the generics through `createSlice`
1001 */
1002 type NormalizedQueryUpsertEntryPayload = {
1003 endpointName: string;
1004 arg: unknown;
1005 value: unknown;
1006 };
1007 type ProcessedQueryUpsertEntry = {
1008 queryDescription: QueryThunkArg;
1009 value: unknown;
1010 };
1011 /**
1012 * A typesafe representation of a util action creator that accepts cache entry descriptions to upsert
1013 */
1014 type UpsertEntries<Definitions extends EndpointDefinitions> = (<EndpointNames extends Array<AllQueryKeys<Definitions>>>(entries: [
1015 ...{
1016 [I in keyof EndpointNames]: NormalizedQueryUpsertEntry<Definitions, EndpointNames[I]>;
1017 }
1018 ]) => PayloadAction<NormalizedQueryUpsertEntryPayload[]>) & {
1019 match: (action: unknown) => action is PayloadAction<NormalizedQueryUpsertEntryPayload[]>;
1020 };
1021 declare function buildSlice({ reducerPath, queryThunk, mutationThunk, serializeQueryArgs, context: { endpointDefinitions: definitions, apiUid, extractRehydrationInfo, hasRehydrationInfo, }, assertTagType, config, }: {
1022 reducerPath: string;
1023 queryThunk: QueryThunk;
1024 infiniteQueryThunk: InfiniteQueryThunk<any>;
1025 mutationThunk: MutationThunk;
1026 serializeQueryArgs: InternalSerializeQueryArgs;
1027 context: ApiContext<EndpointDefinitions>;
1028 assertTagType: AssertTagTypes;
1029 config: Omit<ConfigState<string>, 'online' | 'focused' | 'middlewareRegistered'>;
1030 }): {
1031 reducer: redux.Reducer<{
1032 queries: QueryState<any>;
1033 mutations: MutationState<any>;
1034 provided: InvalidationState<string>;
1035 subscriptions: SubscriptionState;
1036 config: ConfigState<string>;
1037 }, redux.UnknownAction, Partial<{
1038 queries: QueryState<any> | undefined;
1039 mutations: MutationState<any> | undefined;
1040 provided: InvalidationState<string> | undefined;
1041 subscriptions: SubscriptionState | undefined;
1042 config: ConfigState<string> | undefined;
1043 }>>;
1044 actions: {
1045 resetApiState: _reduxjs_toolkit.ActionCreatorWithoutPayload<`${string}/resetApiState`>;
1046 updateProvidedBy: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: {
1047 queryCacheKey: QueryCacheKey;
1048 providedTags: readonly FullTagDescription<string>[];
1049 }], {
1050 queryCacheKey: QueryCacheKey;
1051 providedTags: readonly FullTagDescription<string>[];
1052 }, `${string}/invalidation/updateProvidedBy`, never, unknown>;
1053 removeMutationResult: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: MutationSubstateIdentifier], MutationSubstateIdentifier, `${string}/mutations/removeMutationResult`, never, unknown>;
1054 subscriptionsUpdated: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: Patch[]], Patch[], `${string}/internalSubscriptions/subscriptionsUpdated`, never, unknown>;
1055 updateSubscriptionOptions: _reduxjs_toolkit.ActionCreatorWithPayload<{
1056 endpointName: string;
1057 requestId: string;
1058 options: Subscribers[number];
1059 } & QuerySubstateIdentifier, `${string}/subscriptions/updateSubscriptionOptions`>;
1060 unsubscribeQueryResult: _reduxjs_toolkit.ActionCreatorWithPayload<{
1061 requestId: string;
1062 } & QuerySubstateIdentifier, `${string}/subscriptions/unsubscribeQueryResult`>;
1063 internal_getRTKQSubscriptions: _reduxjs_toolkit.ActionCreatorWithoutPayload<`${string}/subscriptions/internal_getRTKQSubscriptions`>;
1064 removeQueryResult: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: QuerySubstateIdentifier], QuerySubstateIdentifier, `${string}/queries/removeQueryResult`, never, unknown>;
1065 cacheEntriesUpserted: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: NormalizedQueryUpsertEntryPayload[]], ProcessedQueryUpsertEntry[], `${string}/queries/cacheEntriesUpserted`, never, {
1066 RTK_autoBatch: boolean;
1067 requestId: string;
1068 timestamp: number;
1069 }>;
1070 queryResultPatched: _reduxjs_toolkit.ActionCreatorWithPreparedPayload<[payload: QuerySubstateIdentifier & {
1071 patches: readonly Patch[];
1072 }], QuerySubstateIdentifier & {
1073 patches: readonly Patch[];
1074 }, `${string}/queries/queryResultPatched`, never, unknown>;
1075 middlewareRegistered: _reduxjs_toolkit.ActionCreatorWithPayload<string, `${string}/config/middlewareRegistered`>;
1076 };
1077 };
1078 type SliceActions = ReturnType<typeof buildSlice>['actions'];
1079
1080 declare const onFocus: ActionCreatorWithoutPayload<"__rtkq/focused">;
1081 declare const onFocusLost: ActionCreatorWithoutPayload<"__rtkq/unfocused">;
1082 declare const onOnline: ActionCreatorWithoutPayload<"__rtkq/online">;
1083 declare const onOffline: ActionCreatorWithoutPayload<"__rtkq/offline">;
1084 /**
1085 * A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.
1086 * It requires the dispatch method from your store.
1087 * Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,
1088 * but you have the option of providing a callback for more granular control.
1089 *
1090 * @example
1091 * ```ts
1092 * setupListeners(store.dispatch)
1093 * ```
1094 *
1095 * @param dispatch - The dispatch method from your store
1096 * @param customHandler - An optional callback for more granular control over listener behavior
1097 * @returns Return value of the handler.
1098 * The default handler returns an `unsubscribe` method that can be called to remove the listeners.
1099 */
1100 declare function setupListeners(dispatch: ThunkDispatch<any, any, any>, customHandler?: (dispatch: ThunkDispatch<any, any, any>, actions: {
1101 onFocus: typeof onFocus;
1102 onFocusLost: typeof onFocusLost;
1103 onOnline: typeof onOnline;
1104 onOffline: typeof onOffline;
1105 }) => () => void): () => void;
1106
1107 /**
1108 * Note: this file should import all other files for type discovery and declaration merging
1109 */
1110
1111 /**
1112 * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_
1113 * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value
1114 *
1115 * @overloadSummary
1116 * `force`
1117 * - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.
1118 */
1119 type PrefetchOptions = {
1120 ifOlderThan?: false | number;
1121 } | {
1122 force?: boolean;
1123 };
1124 export declare const coreModuleName: unique symbol;
1125 type CoreModule = typeof coreModuleName | ReferenceCacheLifecycle | ReferenceQueryLifecycle | ReferenceCacheCollection;
1126 type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>;
1127 interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
1128 [coreModuleName]: {
1129 /**
1130 * This api's reducer should be mounted at `store[api.reducerPath]`.
1131 *
1132 * @example
1133 * ```ts
1134 * configureStore({
1135 * reducer: {
1136 * [api.reducerPath]: api.reducer,
1137 * },
1138 * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
1139 * })
1140 * ```
1141 */
1142 reducerPath: ReducerPath;
1143 /**
1144 * Internal actions not part of the public API. Note: These are subject to change at any given time.
1145 */
1146 internalActions: InternalActions;
1147 /**
1148 * A standard redux reducer that enables core functionality. Make sure it's included in your store.
1149 *
1150 * @example
1151 * ```ts
1152 * configureStore({
1153 * reducer: {
1154 * [api.reducerPath]: api.reducer,
1155 * },
1156 * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
1157 * })
1158 * ```
1159 */
1160 reducer: Reducer<CombinedState<Definitions, TagTypes, ReducerPath>, UnknownAction>;
1161 /**
1162 * This is a standard redux middleware and is responsible for things like polling, garbage collection and a handful of other things. Make sure it's included in your store.
1163 *
1164 * @example
1165 * ```ts
1166 * configureStore({
1167 * reducer: {
1168 * [api.reducerPath]: api.reducer,
1169 * },
1170 * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
1171 * })
1172 * ```
1173 */
1174 middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, UnknownAction>>;
1175 /**
1176 * A collection of utility thunks for various situations.
1177 */
1178 util: {
1179 /**
1180 * A thunk that (if dispatched) will return a specific running query, identified
1181 * by `endpointName` and `arg`.
1182 * If that query is not running, dispatching the thunk will result in `undefined`.
1183 *
1184 * Can be used to await a specific query triggered in any way,
1185 * including via hook calls or manually dispatching `initiate` actions.
1186 *
1187 * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
1188 */
1189 getRunningQueryThunk<EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>): ThunkWithReturnValue<QueryActionCreatorResult<Definitions[EndpointName] & {
1190 type: 'query';
1191 }> | InfiniteQueryActionCreatorResult<Definitions[EndpointName] & {
1192 type: 'infinitequery';
1193 }> | undefined>;
1194 /**
1195 * A thunk that (if dispatched) will return a specific running mutation, identified
1196 * by `endpointName` and `fixedCacheKey` or `requestId`.
1197 * If that mutation is not running, dispatching the thunk will result in `undefined`.
1198 *
1199 * Can be used to await a specific mutation triggered in any way,
1200 * including via hook trigger functions or manually dispatching `initiate` actions.
1201 *
1202 * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
1203 */
1204 getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(endpointName: EndpointName, fixedCacheKeyOrRequestId: string): ThunkWithReturnValue<MutationActionCreatorResult<Definitions[EndpointName] & {
1205 type: 'mutation';
1206 }> | undefined>;
1207 /**
1208 * A thunk that (if dispatched) will return all running queries.
1209 *
1210 * Useful for SSR scenarios to await all running queries triggered in any way,
1211 * including via hook calls or manually dispatching `initiate` actions.
1212 *
1213 * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
1214 */
1215 getRunningQueriesThunk(): ThunkWithReturnValue<Array<QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>>;
1216 /**
1217 * A thunk that (if dispatched) will return all running mutations.
1218 *
1219 * Useful for SSR scenarios to await all running mutations triggered in any way,
1220 * including via hook calls or manually dispatching `initiate` actions.
1221 *
1222 * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
1223 */
1224 getRunningMutationsThunk(): ThunkWithReturnValue<Array<MutationActionCreatorResult<any>>>;
1225 /**
1226 * A Redux thunk that can be used to manually trigger pre-fetching of data.
1227 *
1228 * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.
1229 *
1230 * React Hooks users will most likely never need to use this directly, as the `usePrefetch` hook will dispatch this thunk internally as needed when you call the prefetching function supplied by the hook.
1231 *
1232 * @example
1233 *
1234 * ```ts no-transpile
1235 * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))
1236 * ```
1237 */
1238 prefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, options: PrefetchOptions): ThunkAction<void, any, any, UnknownAction>;
1239 /**
1240 * A Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes.
1241 *
1242 * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and an `updateRecipe` callback function. The callback receives an Immer-wrapped `draft` of the current state, and may modify the draft to match the expected results after the mutation completes successfully.
1243 *
1244 * The thunk executes _synchronously_, and returns an object containing `{patches: Patch[], inversePatches: Patch[], undo: () => void}`. The `patches` and `inversePatches` are generated using Immer's [`produceWithPatches` method](https://immerjs.github.io/immer/patches).
1245 *
1246 * This is typically used as the first step in implementing optimistic updates. The generated `inversePatches` can be used to revert the updates by calling `dispatch(patchQueryData(endpointName, arg, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.
1247 *
1248 * Note that the first two arguments (`endpointName` and `arg`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.
1249 *
1250 * @example
1251 *
1252 * ```ts
1253 * const patchCollection = dispatch(
1254 * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
1255 * draftPosts.push({ id: 1, name: 'Teddy' })
1256 * })
1257 * )
1258 * ```
1259 */
1260 updateQueryData: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
1261 /**
1262 * A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.
1263 *
1264 * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and the data to upsert.
1265 *
1266 * If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.
1267 *
1268 * The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.
1269 *
1270 * If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a "last result wins" update behavior.
1271 *
1272 * @example
1273 *
1274 * ```ts
1275 * await dispatch(
1276 * api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: "Hello!"})
1277 * )
1278 * ```
1279 */
1280 upsertQueryData: UpsertQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
1281 /**
1282 * A Redux thunk that applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.
1283 *
1284 * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.
1285 *
1286 * This is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching `patchQueryData` with the `inversePatches` that were generated by `updateQueryData` earlier.
1287 *
1288 * In cases where it is desired to simply revert the previous changes, it may be preferable to call the `undo` method returned from dispatching `updateQueryData` instead.
1289 *
1290 * @example
1291 * ```ts
1292 * const patchCollection = dispatch(
1293 * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
1294 * draftPosts.push({ id: 1, name: 'Teddy' })
1295 * })
1296 * )
1297 *
1298 * // later
1299 * dispatch(
1300 * api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)
1301 * )
1302 *
1303 * // or
1304 * patchCollection.undo()
1305 * ```
1306 */
1307 patchQueryData: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
1308 /**
1309 * A Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.
1310 *
1311 * @example
1312 *
1313 * ```ts
1314 * dispatch(api.util.resetApiState())
1315 * ```
1316 */
1317 resetApiState: SliceActions['resetApiState'];
1318 upsertQueryEntries: UpsertEntries<Definitions>;
1319 /**
1320 * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).
1321 *
1322 * The action creator accepts one argument: the cache tags to be invalidated. It returns an action with those tags as a payload, and the corresponding `invalidateTags` action type for the api.
1323 *
1324 * Dispatching the result of this action creator will [invalidate](../../usage/automated-refetching.mdx#invalidating-cache-data) the given tags, causing queries to automatically re-fetch if they are subscribed to cache data that [provides](../../usage/automated-refetching.mdx#providing-cache-data) the corresponding tags.
1325 *
1326 * The array of tags provided to the action creator should be in one of the following formats, where `TagType` is equal to a string provided to the [`tagTypes`](../createApi.mdx#tagtypes) property of the api:
1327 *
1328 * - `[TagType]`
1329 * - `[{ type: TagType }]`
1330 * - `[{ type: TagType, id: number | string }]`
1331 *
1332 * @example
1333 *
1334 * ```ts
1335 * dispatch(api.util.invalidateTags(['Post']))
1336 * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))
1337 * dispatch(
1338 * api.util.invalidateTags([
1339 * { type: 'Post', id: 1 },
1340 * { type: 'Post', id: 'LIST' },
1341 * ])
1342 * )
1343 * ```
1344 */
1345 invalidateTags: ActionCreatorWithPayload<Array<TagDescription<TagTypes> | null | undefined>, string>;
1346 /**
1347 * A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.
1348 *
1349 * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.
1350 */
1351 selectInvalidatedBy: (state: RootState<Definitions, string, ReducerPath>, tags: ReadonlyArray<TagDescription<TagTypes> | null | undefined>) => Array<{
1352 endpointName: string;
1353 originalArgs: any;
1354 queryCacheKey: string;
1355 }>;
1356 /**
1357 * A function to select all arguments currently cached for a given endpoint.
1358 *
1359 * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.
1360 */
1361 selectCachedArgsForQuery: <QueryName extends AllQueryKeys<Definitions>>(state: RootState<Definitions, string, ReducerPath>, queryName: QueryName) => Array<QueryArgFromAnyQuery<Definitions[QueryName]>>;
1362 };
1363 /**
1364 * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.
1365 */
1366 endpoints: {
1367 [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? ApiEndpointQuery<Definitions[K], Definitions> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? ApiEndpointMutation<Definitions[K], Definitions> : Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? ApiEndpointInfiniteQuery<Definitions[K], Definitions> : never;
1368 };
1369 };
1370 }
1371 interface ApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> extends BuildThunksApiEndpointQuery<Definition>, BuildInitiateApiEndpointQuery<Definition>, BuildSelectorsApiEndpointQuery<Definition, Definitions> {
1372 name: string;
1373 /**
1374 * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
1375 */
1376 Types: NonNullable<Definition['Types']>;
1377 }
1378 interface ApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> extends BuildThunksApiEndpointInfiniteQuery<Definition>, BuildInitiateApiEndpointInfiniteQuery<Definition>, BuildSelectorsApiEndpointInfiniteQuery<Definition, Definitions> {
1379 name: string;
1380 /**
1381 * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
1382 */
1383 Types: NonNullable<Definition['Types']>;
1384 }
1385 interface ApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> extends BuildThunksApiEndpointMutation<Definition>, BuildInitiateApiEndpointMutation<Definition>, BuildSelectorsApiEndpointMutation<Definition, Definitions> {
1386 name: string;
1387 /**
1388 * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
1389 */
1390 Types: NonNullable<Definition['Types']>;
1391 }
1392 type ListenerActions = {
1393 /**
1394 * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior
1395 * @link https://rtk-query-docs.netlify.app/api/setupListeners
1396 */
1397 onOnline: typeof onOnline;
1398 onOffline: typeof onOffline;
1399 /**
1400 * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior
1401 * @link https://rtk-query-docs.netlify.app/api/setupListeners
1402 */
1403 onFocus: typeof onFocus;
1404 onFocusLost: typeof onFocusLost;
1405 };
1406 type InternalActions = SliceActions & ListenerActions;
1407 interface CoreModuleOptions {
1408 /**
1409 * A selector creator (usually from `reselect`, or matching the same signature)
1410 */
1411 createSelector?: typeof createSelector;
1412 }
1413 /**
1414 * Creates a module containing the basic redux logic for use with `buildCreateApi`.
1415 *
1416 * @example
1417 * ```ts
1418 * const createBaseApi = buildCreateApi(coreModule());
1419 * ```
1420 */
1421 declare const coreModule: ({ createSelector, }?: CoreModuleOptions) => Module<CoreModule>;
1422
1423 declare const createApi: CreateApi<typeof coreModuleName>;
1424
1425 type ModuleName = keyof ApiModules<any, any, any, any>;
1426 type Module<Name extends ModuleName> = {
1427 name: Name;
1428 init<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string>(api: Api<BaseQuery, EndpointDefinitions, ReducerPath, TagTypes, ModuleName>, options: WithRequiredProp<CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>, 'reducerPath' | 'serializeQueryArgs' | 'keepUnusedDataFor' | 'refetchOnMountOrArgChange' | 'refetchOnFocus' | 'refetchOnReconnect' | 'invalidationBehavior' | 'tagTypes'>, context: ApiContext<Definitions>): {
1429 injectEndpoint(endpointName: string, definition: EndpointDefinition<any, any, any, any>): void;
1430 };
1431 };
1432 interface ApiContext<Definitions extends EndpointDefinitions> {
1433 apiUid: string;
1434 endpointDefinitions: Definitions;
1435 batch(cb: () => void): void;
1436 extractRehydrationInfo: (action: UnknownAction) => CombinedState<any, any, any> | undefined;
1437 hasRehydrationInfo: (action: UnknownAction) => boolean;
1438 }
1439 type Api<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string, Enhancers extends ModuleName = CoreModule> = UnionToIntersection<ApiModules<BaseQuery, Definitions, ReducerPath, TagTypes>[Enhancers]> & {
1440 /**
1441 * A function to inject the endpoints into the original API, but also give you that same API with correct types for these endpoints back. Useful with code-splitting.
1442 */
1443 injectEndpoints<NewDefinitions extends EndpointDefinitions>(_: {
1444 endpoints: (build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>) => NewDefinitions;
1445 /**
1446 * Optionally allows endpoints to be overridden if defined by multiple `injectEndpoints` calls.
1447 *
1448 * If set to `true`, will override existing endpoints with the new definition.
1449 * If set to `'throw'`, will throw an error if an endpoint is redefined with a different definition.
1450 * If set to `false` (or unset), will not override existing endpoints with the new definition, and log a warning in development.
1451 */
1452 overrideExisting?: boolean | 'throw';
1453 }): Api<BaseQuery, Definitions & NewDefinitions, ReducerPath, TagTypes, Enhancers>;
1454 /**
1455 *A function to enhance a generated API with additional information. Useful with code-generation.
1456 */
1457 enhanceEndpoints<NewTagTypes extends string = never, NewDefinitions extends EndpointDefinitions = never>(_: {
1458 addTagTypes?: readonly NewTagTypes[];
1459 endpoints?: UpdateDefinitions<Definitions, TagTypes | NoInfer<NewTagTypes>, NewDefinitions> extends infer NewDefinitions ? {
1460 [K in keyof NewDefinitions]?: Partial<NewDefinitions[K]> | ((definition: NewDefinitions[K]) => void);
1461 } : never;
1462 }): Api<BaseQuery, UpdateDefinitions<Definitions, TagTypes | NewTagTypes, NewDefinitions>, ReducerPath, TagTypes | NewTagTypes, Enhancers>;
1463 };
1464
1465 type PromiseWithKnownReason<T, R> = Omit<Promise<T>, 'then' | 'catch'> & {
1466 /**
1467 * Attaches callbacks for the resolution and/or rejection of the Promise.
1468 * @param onfulfilled The callback to execute when the Promise is resolved.
1469 * @param onrejected The callback to execute when the Promise is rejected.
1470 * @returns A Promise for the completion of which ever callback is executed.
1471 */
1472 then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: R) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
1473 /**
1474 * Attaches a callback for only the rejection of the Promise.
1475 * @param onrejected The callback to execute when the Promise is rejected.
1476 * @returns A Promise for the completion of the callback.
1477 */
1478 catch<TResult = never>(onrejected?: ((reason: R) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
1479 };
1480
1481 type ReferenceCacheCollection = never;
1482 type CacheCollectionQueryExtraOptions = {
1483 /**
1484 * Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(This value is in seconds.)_
1485 *
1486 * This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.
1487 */
1488 keepUnusedDataFor?: number;
1489 };
1490
1491 export declare const _NEVER: unique symbol;
1492 type NEVER = typeof _NEVER;
1493 /**
1494 * Creates a "fake" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.
1495 * This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.
1496 */
1497 declare function fakeBaseQuery<ErrorType>(): BaseQueryFn<void, NEVER, ErrorType, {}>;
1498
1499 declare const resultType: unique symbol;
1500 declare const baseQuery: unique symbol;
1501 type EndpointDefinitionWithQuery<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {
1502 /**
1503 * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.
1504 *
1505 * @example
1506 *
1507 * ```ts
1508 * // codeblock-meta title="query example"
1509 *
1510 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
1511 * interface Post {
1512 * id: number
1513 * name: string
1514 * }
1515 * type PostsResponse = Post[]
1516 *
1517 * const api = createApi({
1518 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
1519 * tagTypes: ['Post'],
1520 * endpoints: (build) => ({
1521 * getPosts: build.query<PostsResponse, void>({
1522 * // highlight-start
1523 * query: () => 'posts',
1524 * // highlight-end
1525 * }),
1526 * addPost: build.mutation<Post, Partial<Post>>({
1527 * // highlight-start
1528 * query: (body) => ({
1529 * url: `posts`,
1530 * method: 'POST',
1531 * body,
1532 * }),
1533 * // highlight-end
1534 * invalidatesTags: [{ type: 'Post', id: 'LIST' }],
1535 * }),
1536 * })
1537 * })
1538 * ```
1539 */
1540 query(arg: QueryArg): BaseQueryArg<BaseQuery>;
1541 queryFn?: never;
1542 /**
1543 * A function to manipulate the data returned by a query or mutation.
1544 */
1545 transformResponse?(baseQueryReturnValue: BaseQueryResult<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): ResultType | Promise<ResultType>;
1546 /**
1547 * A function to manipulate the data returned by a failed query or mutation.
1548 */
1549 transformErrorResponse?(baseQueryReturnValue: BaseQueryError<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): unknown;
1550 /**
1551 * Defaults to `true`.
1552 *
1553 * Most apps should leave this setting on. The only time it can be a performance issue
1554 * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and
1555 * you're unable to paginate it.
1556 *
1557 * For details of how this works, please see the below. When it is set to `false`,
1558 * every request will cause subscribed components to rerender, even when the data has not changed.
1559 *
1560 * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing
1561 */
1562 structuralSharing?: boolean;
1563 };
1564 type EndpointDefinitionWithQueryFn<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {
1565 /**
1566 * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.
1567 *
1568 * @example
1569 * ```ts
1570 * // codeblock-meta title="Basic queryFn example"
1571 *
1572 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
1573 * interface Post {
1574 * id: number
1575 * name: string
1576 * }
1577 * type PostsResponse = Post[]
1578 *
1579 * const api = createApi({
1580 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
1581 * endpoints: (build) => ({
1582 * getPosts: build.query<PostsResponse, void>({
1583 * query: () => 'posts',
1584 * }),
1585 * flipCoin: build.query<'heads' | 'tails', void>({
1586 * // highlight-start
1587 * queryFn(arg, queryApi, extraOptions, baseQuery) {
1588 * const randomVal = Math.random()
1589 * if (randomVal < 0.45) {
1590 * return { data: 'heads' }
1591 * }
1592 * if (randomVal < 0.9) {
1593 * return { data: 'tails' }
1594 * }
1595 * return { error: { status: 500, statusText: 'Internal Server Error', data: "Coin landed on its edge!" } }
1596 * }
1597 * // highlight-end
1598 * })
1599 * })
1600 * })
1601 * ```
1602 */
1603 queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions<BaseQuery>, baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>>;
1604 query?: never;
1605 transformResponse?: never;
1606 transformErrorResponse?: never;
1607 /**
1608 * Defaults to `true`.
1609 *
1610 * Most apps should leave this setting on. The only time it can be a performance issue
1611 * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and
1612 * you're unable to paginate it.
1613 *
1614 * For details of how this works, please see the below. When it is set to `false`,
1615 * every request will cause subscribed components to rerender, even when the data has not changed.
1616 *
1617 * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing
1618 */
1619 structuralSharing?: boolean;
1620 };
1621 type BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {
1622 QueryArg: QueryArg;
1623 BaseQuery: BaseQuery;
1624 ResultType: ResultType;
1625 };
1626 type BaseEndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = (([CastAny<BaseQueryResult<BaseQuery>, {}>] extends [NEVER] ? never : EndpointDefinitionWithQuery<QueryArg, BaseQuery, ResultType>) | EndpointDefinitionWithQueryFn<QueryArg, BaseQuery, ResultType>) & {
1627 [resultType]?: ResultType;
1628 [baseQuery]?: BaseQuery;
1629 } & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {
1630 extraOptions: BaseQueryExtraOptions<BaseQuery>;
1631 }, {
1632 extraOptions?: BaseQueryExtraOptions<BaseQuery>;
1633 }>;
1634 declare enum DefinitionType {
1635 query = "query",
1636 mutation = "mutation",
1637 infinitequery = "infinitequery"
1638 }
1639 type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => ReadonlyArray<TagDescription<TagTypes> | undefined | null>;
1640 type FullTagDescription<TagType> = {
1641 type: TagType;
1642 id?: number | string;
1643 };
1644 type TagDescription<TagType> = TagType | FullTagDescription<TagType>;
1645 /**
1646 * @public
1647 */
1648 type ResultDescription<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = ReadonlyArray<TagDescription<TagTypes> | undefined | null> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>;
1649 type QueryTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType> & {
1650 /**
1651 * The endpoint definition type. To be used with some internal generic types.
1652 * @example
1653 * ```ts
1654 * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...
1655 * ```
1656 */
1657 QueryDefinition: QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
1658 TagTypes: TagTypes;
1659 ReducerPath: ReducerPath;
1660 };
1661 /**
1662 * @public
1663 */
1664 interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> extends CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {
1665 type: DefinitionType.query;
1666 /**
1667 * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.
1668 * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.
1669 * 1. `['Post']` - equivalent to `2`
1670 * 2. `[{ type: 'Post' }]` - equivalent to `1`
1671 * 3. `[{ type: 'Post', id: 1 }]`
1672 * 4. `(result, error, arg) => ['Post']` - equivalent to `5`
1673 * 5. `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`
1674 * 6. `(result, error, arg) => [{ type: 'Post', id: 1 }]`
1675 *
1676 * @example
1677 *
1678 * ```ts
1679 * // codeblock-meta title="providesTags example"
1680 *
1681 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
1682 * interface Post {
1683 * id: number
1684 * name: string
1685 * }
1686 * type PostsResponse = Post[]
1687 *
1688 * const api = createApi({
1689 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
1690 * tagTypes: ['Posts'],
1691 * endpoints: (build) => ({
1692 * getPosts: build.query<PostsResponse, void>({
1693 * query: () => 'posts',
1694 * // highlight-start
1695 * providesTags: (result) =>
1696 * result
1697 * ? [
1698 * ...result.map(({ id }) => ({ type: 'Posts' as const, id })),
1699 * { type: 'Posts', id: 'LIST' },
1700 * ]
1701 * : [{ type: 'Posts', id: 'LIST' }],
1702 * // highlight-end
1703 * })
1704 * })
1705 * })
1706 * ```
1707 */
1708 providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;
1709 /**
1710 * Not to be used. A query should not invalidate tags in the cache.
1711 */
1712 invalidatesTags?: never;
1713 /**
1714 * Can be provided to return a custom cache key value based on the query arguments.
1715 *
1716 * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key. It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.
1717 *
1718 * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean. If it returns a string, that value will be used as the cache key directly. If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`. This simplifies the use case of stripping out args you don't want included in the cache key.
1719 *
1720 *
1721 * @example
1722 *
1723 * ```ts
1724 * // codeblock-meta title="serializeQueryArgs : exclude value"
1725 *
1726 * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
1727 * interface Post {
1728 * id: number
1729 * name: string
1730 * }
1731 *
1732 * interface MyApiClient {
1733 * fetchPost: (id: string) => Promise<Post>
1734 * }
1735 *
1736 * createApi({
1737 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
1738 * endpoints: (build) => ({
1739 * // Example: an endpoint with an API client passed in as an argument,
1740 * // but only the item ID should be used as the cache key
1741 * getPost: build.query<Post, { id: string; client: MyApiClient }>({
1742 * queryFn: async ({ id, client }) => {
1743 * const post = await client.fetchPost(id)
1744 * return { data: post }
1745 * },
1746 * // highlight-start
1747 * serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {
1748 * const { id } = queryArgs
1749 * // This can return a string, an object, a number, or a boolean.
1750 * // If it returns an object, number or boolean, that value
1751 * // will be serialized automatically via `defaultSerializeQueryArgs`
1752 * return { id } // omit `client` from the cache key
1753 *
1754 * // Alternately, you can use `defaultSerializeQueryArgs` yourself:
1755 * // return defaultSerializeQueryArgs({
1756 * // endpointName,
1757 * // queryArgs: { id },
1758 * // endpointDefinition
1759 * // })
1760 * // Or create and return a string yourself:
1761 * // return `getPost(${id})`
1762 * },
1763 * // highlight-end
1764 * }),
1765 * }),
1766 *})
1767 * ```
1768 */
1769 serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;
1770 /**
1771 * Can be provided to merge an incoming response value into the current cache data.
1772 * If supplied, no automatic structural sharing will be applied - it's up to
1773 * you to update the cache appropriately.
1774 *
1775 * Since RTKQ normally replaces cache entries with the new response, you will usually
1776 * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep
1777 * an existing cache entry so that it can be updated.
1778 *
1779 * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,
1780 * or return a new value, but _not_ both at once.
1781 *
1782 * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,
1783 * the cache entry will just save the response data directly.
1784 *
1785 * Useful if you don't want a new request to completely override the current cache value,
1786 * maybe because you have manually updated it from another source and don't want those
1787 * updates to get lost.
1788 *
1789 *
1790 * @example
1791 *
1792 * ```ts
1793 * // codeblock-meta title="merge: pagination"
1794 *
1795 * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
1796 * interface Post {
1797 * id: number
1798 * name: string
1799 * }
1800 *
1801 * createApi({
1802 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
1803 * endpoints: (build) => ({
1804 * listItems: build.query<string[], number>({
1805 * query: (pageNumber) => `/listItems?page=${pageNumber}`,
1806 * // Only have one cache entry because the arg always maps to one string
1807 * serializeQueryArgs: ({ endpointName }) => {
1808 * return endpointName
1809 * },
1810 * // Always merge incoming data to the cache entry
1811 * merge: (currentCache, newItems) => {
1812 * currentCache.push(...newItems)
1813 * },
1814 * // Refetch when the page arg changes
1815 * forceRefetch({ currentArg, previousArg }) {
1816 * return currentArg !== previousArg
1817 * },
1818 * }),
1819 * }),
1820 *})
1821 * ```
1822 */
1823 merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: {
1824 arg: QueryArg;
1825 baseQueryMeta: BaseQueryMeta<BaseQuery>;
1826 requestId: string;
1827 fulfilledTimeStamp: number;
1828 }): ResultType | void;
1829 /**
1830 * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.
1831 * This is primarily useful for "infinite scroll" / pagination use cases where
1832 * RTKQ is keeping a single cache entry that is added to over time, in combination
1833 * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback
1834 * set to add incoming data to the cache entry each time.
1835 *
1836 * @example
1837 *
1838 * ```ts
1839 * // codeblock-meta title="forceRefresh: pagination"
1840 *
1841 * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
1842 * interface Post {
1843 * id: number
1844 * name: string
1845 * }
1846 *
1847 * createApi({
1848 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
1849 * endpoints: (build) => ({
1850 * listItems: build.query<string[], number>({
1851 * query: (pageNumber) => `/listItems?page=${pageNumber}`,
1852 * // Only have one cache entry because the arg always maps to one string
1853 * serializeQueryArgs: ({ endpointName }) => {
1854 * return endpointName
1855 * },
1856 * // Always merge incoming data to the cache entry
1857 * merge: (currentCache, newItems) => {
1858 * currentCache.push(...newItems)
1859 * },
1860 * // Refetch when the page arg changes
1861 * forceRefetch({ currentArg, previousArg }) {
1862 * return currentArg !== previousArg
1863 * },
1864 * }),
1865 * }),
1866 *})
1867 * ```
1868 */
1869 forceRefetch?(params: {
1870 currentArg: QueryArg | undefined;
1871 previousArg: QueryArg | undefined;
1872 state: RootState<any, any, string>;
1873 endpointState?: QuerySubState<any>;
1874 }): boolean;
1875 /**
1876 * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
1877 */
1878 Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
1879 }
1880 type QueryDefinition<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> & QueryExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>;
1881 type InfiniteQueryTypes<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType> & {
1882 /**
1883 * The endpoint definition type. To be used with some internal generic types.
1884 * @example
1885 * ```ts
1886 * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...
1887 * ```
1888 */
1889 InfiniteQueryDefinition: InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;
1890 TagTypes: TagTypes;
1891 ReducerPath: ReducerPath;
1892 };
1893 interface InfiniteQueryExtraOptions<TagTypes extends string, ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> extends CacheLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {
1894 type: DefinitionType.infinitequery;
1895 providesTags?: ResultDescription<TagTypes, InfiniteData<ResultType, PageParam>, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;
1896 /**
1897 * Not to be used. A query should not invalidate tags in the cache.
1898 */
1899 invalidatesTags?: never;
1900 /**
1901 * Required options to configure the infinite query behavior.
1902 * `initialPageParam` and `getNextPageParam` are required, to
1903 * ensure the infinite query can properly fetch the next page of data.
1904 * `initialPageParam` may be specified when using the
1905 * endpoint, to override the default value.
1906 * `maxPages` and `getPreviousPageParam` are both optional.
1907 *
1908 * @example
1909 *
1910 * ```ts
1911 * // codeblock-meta title="infiniteQueryOptions example"
1912 * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
1913 *
1914 * type Pokemon = {
1915 * id: string
1916 * name: string
1917 * }
1918 *
1919 * const pokemonApi = createApi({
1920 * baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
1921 * endpoints: (build) => ({
1922 * getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({
1923 * infiniteQueryOptions: {
1924 * initialPageParam: 0,
1925 * maxPages: 3,
1926 * getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>
1927 * lastPageParam + 1,
1928 * getPreviousPageParam: (
1929 * firstPage,
1930 * allPages,
1931 * firstPageParam,
1932 * allPageParams,
1933 * ) => {
1934 * return firstPageParam > 0 ? firstPageParam - 1 : undefined
1935 * },
1936 * },
1937 * query({pageParam}) {
1938 * return `https://example.com/listItems?page=${pageParam}`
1939 * },
1940 * }),
1941 * }),
1942 * })
1943
1944 * ```
1945 */
1946 infiniteQueryOptions: InfiniteQueryConfigOptions<ResultType, PageParam>;
1947 /**
1948 * Can be provided to return a custom cache key value based on the query arguments.
1949 *
1950 * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key. It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.
1951 *
1952 * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean. If it returns a string, that value will be used as the cache key directly. If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`. This simplifies the use case of stripping out args you don't want included in the cache key.
1953 *
1954 *
1955 * @example
1956 *
1957 * ```ts
1958 * // codeblock-meta title="serializeQueryArgs : exclude value"
1959 *
1960 * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
1961 * interface Post {
1962 * id: number
1963 * name: string
1964 * }
1965 *
1966 * interface MyApiClient {
1967 * fetchPost: (id: string) => Promise<Post>
1968 * }
1969 *
1970 * createApi({
1971 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
1972 * endpoints: (build) => ({
1973 * // Example: an endpoint with an API client passed in as an argument,
1974 * // but only the item ID should be used as the cache key
1975 * getPost: build.query<Post, { id: string; client: MyApiClient }>({
1976 * queryFn: async ({ id, client }) => {
1977 * const post = await client.fetchPost(id)
1978 * return { data: post }
1979 * },
1980 * // highlight-start
1981 * serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {
1982 * const { id } = queryArgs
1983 * // This can return a string, an object, a number, or a boolean.
1984 * // If it returns an object, number or boolean, that value
1985 * // will be serialized automatically via `defaultSerializeQueryArgs`
1986 * return { id } // omit `client` from the cache key
1987 *
1988 * // Alternately, you can use `defaultSerializeQueryArgs` yourself:
1989 * // return defaultSerializeQueryArgs({
1990 * // endpointName,
1991 * // queryArgs: { id },
1992 * // endpointDefinition
1993 * // })
1994 * // Or create and return a string yourself:
1995 * // return `getPost(${id})`
1996 * },
1997 * // highlight-end
1998 * }),
1999 * }),
2000 *})
2001 * ```
2002 */
2003 serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;
2004 /**
2005 * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
2006 */
2007 Types?: InfiniteQueryTypes<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;
2008 }
2009 type InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointDefinition<InfiniteQueryCombinedArg<QueryArg, PageParam>, BaseQuery, ResultType> & InfiniteQueryExtraOptions<TagTypes, ResultType, QueryArg, PageParam, BaseQuery, ReducerPath>;
2010 type MutationTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType> & {
2011 /**
2012 * The endpoint definition type. To be used with some internal generic types.
2013 * @example
2014 * ```ts
2015 * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...
2016 * ```
2017 */
2018 MutationDefinition: MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
2019 TagTypes: TagTypes;
2020 ReducerPath: ReducerPath;
2021 };
2022 /**
2023 * @public
2024 */
2025 interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> extends CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath> {
2026 type: DefinitionType.mutation;
2027 /**
2028 * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.
2029 * Expects the same shapes as `providesTags`.
2030 *
2031 * @example
2032 *
2033 * ```ts
2034 * // codeblock-meta title="invalidatesTags example"
2035 * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
2036 * interface Post {
2037 * id: number
2038 * name: string
2039 * }
2040 * type PostsResponse = Post[]
2041 *
2042 * const api = createApi({
2043 * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
2044 * tagTypes: ['Posts'],
2045 * endpoints: (build) => ({
2046 * getPosts: build.query<PostsResponse, void>({
2047 * query: () => 'posts',
2048 * providesTags: (result) =>
2049 * result
2050 * ? [
2051 * ...result.map(({ id }) => ({ type: 'Posts' as const, id })),
2052 * { type: 'Posts', id: 'LIST' },
2053 * ]
2054 * : [{ type: 'Posts', id: 'LIST' }],
2055 * }),
2056 * addPost: build.mutation<Post, Partial<Post>>({
2057 * query(body) {
2058 * return {
2059 * url: `posts`,
2060 * method: 'POST',
2061 * body,
2062 * }
2063 * },
2064 * // highlight-start
2065 * invalidatesTags: [{ type: 'Posts', id: 'LIST' }],
2066 * // highlight-end
2067 * }),
2068 * })
2069 * })
2070 * ```
2071 */
2072 invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;
2073 /**
2074 * Not to be used. A mutation should not provide tags to the cache.
2075 */
2076 providesTags?: never;
2077 /**
2078 * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
2079 */
2080 Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
2081 }
2082 type MutationDefinition<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> & MutationExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>;
2083 type EndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, PageParam = any> = QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath> | MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath> | InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;
2084 type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any>>;
2085 type EndpointBuilder<BaseQuery extends BaseQueryFn, TagTypes extends string, ReducerPath extends string> = {
2086 /**
2087 * An endpoint definition that retrieves data, and may provide tags to the cache.
2088 *
2089 * @example
2090 * ```js
2091 * // codeblock-meta title="Example of all query endpoint options"
2092 * const api = createApi({
2093 * baseQuery,
2094 * endpoints: (build) => ({
2095 * getPost: build.query({
2096 * query: (id) => ({ url: `post/${id}` }),
2097 * // Pick out data and prevent nested properties in a hook or selector
2098 * transformResponse: (response) => response.data,
2099 * // Pick out error and prevent nested properties in a hook or selector
2100 * transformErrorResponse: (response) => response.error,
2101 * // `result` is the server response
2102 * providesTags: (result, error, id) => [{ type: 'Post', id }],
2103 * // trigger side effects or optimistic updates
2104 * onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},
2105 * // handle subscriptions etc
2106 * onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},
2107 * }),
2108 * }),
2109 *});
2110 *```
2111 */
2112 query<ResultType, QueryArg>(definition: OmitFromUnion<QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>, 'type'>): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
2113 /**
2114 * An endpoint definition that alters data on the server or will possibly invalidate the cache.
2115 *
2116 * @example
2117 * ```js
2118 * // codeblock-meta title="Example of all mutation endpoint options"
2119 * const api = createApi({
2120 * baseQuery,
2121 * endpoints: (build) => ({
2122 * updatePost: build.mutation({
2123 * query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),
2124 * // Pick out data and prevent nested properties in a hook or selector
2125 * transformResponse: (response) => response.data,
2126 * // Pick out error and prevent nested properties in a hook or selector
2127 * transformErrorResponse: (response) => response.error,
2128 * // `result` is the server response
2129 * invalidatesTags: (result, error, id) => [{ type: 'Post', id }],
2130 * // trigger side effects or optimistic updates
2131 * onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},
2132 * // handle subscriptions etc
2133 * onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},
2134 * }),
2135 * }),
2136 * });
2137 * ```
2138 */
2139 mutation<ResultType, QueryArg>(definition: OmitFromUnion<MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>, 'type'>): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
2140 infiniteQuery<ResultType, QueryArg, PageParam>(definition: OmitFromUnion<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>, 'type'>): InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;
2141 };
2142 type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;
2143 type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any> ? QA : never;
2144 type InfiniteQueryArgFrom<D extends BaseEndpointDefinition<any, any, any>> = D extends InfiniteQueryDefinition<infer QA, any, any, any, any> ? QA : never;
2145 type QueryArgFromAnyQuery<D extends BaseEndpointDefinition<any, any, any>> = D extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryArgFrom<D> : D extends QueryDefinition<any, any, any, any> ? QueryArgFrom<D> : never;
2146 type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT> ? RT : unknown;
2147 type ReducerPathFrom<D extends EndpointDefinition<any, any, any, any, any>> = D extends EndpointDefinition<any, any, any, any, infer RP> ? RP : unknown;
2148 type TagTypesFrom<D extends EndpointDefinition<any, any, any, any>> = D extends EndpointDefinition<any, any, infer RP, any> ? RP : unknown;
2149 type PageParamFrom<D extends InfiniteQueryDefinition<any, any, any, any, any>> = D extends InfiniteQueryDefinition<any, infer PP, any, any, any> ? PP : unknown;
2150 type InfiniteQueryCombinedArg<QueryArg, PageParam> = {
2151 queryArg: QueryArg;
2152 pageParam: PageParam;
2153 };
2154 type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;
2155 type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;
2156 type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;
2157 type OverrideResultType<Definition, NewResultType> = Definition extends QueryDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends MutationDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, NewResultType, ReducerPath> : never;
2158 type UpdateDefinitions<Definitions extends EndpointDefinitions, NewTagTypes extends string, NewDefinitions extends EndpointDefinitions> = {
2159 [K in keyof Definitions]: Definitions[K] extends QueryDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends MutationDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : never;
2160 };
2161
2162 type QueryCacheKey = string & {
2163 _type: 'queryCacheKey';
2164 };
2165 type QuerySubstateIdentifier = {
2166 queryCacheKey: QueryCacheKey;
2167 };
2168 type MutationSubstateIdentifier = {
2169 requestId: string;
2170 fixedCacheKey?: string;
2171 } | {
2172 requestId?: string;
2173 fixedCacheKey: string;
2174 };
2175 type RefetchConfigOptions = {
2176 refetchOnMountOrArgChange: boolean | number;
2177 refetchOnReconnect: boolean;
2178 refetchOnFocus: boolean;
2179 };
2180 type PageParamFunction<DataType, PageParam> = (firstPage: DataType, allPages: Array<DataType>, firstPageParam: PageParam, allPageParams: Array<PageParam>) => PageParam | undefined | null;
2181 type InfiniteQueryConfigOptions<DataType, PageParam> = {
2182 /**
2183 * The initial page parameter to use for the first page fetch.
2184 */
2185 initialPageParam: PageParam;
2186 /**
2187 * This function is required to automatically get the next cursor for infinite queries.
2188 * The result will also be used to determine the value of `hasNextPage`.
2189 */
2190 getNextPageParam: PageParamFunction<DataType, PageParam>;
2191 /**
2192 * This function can be set to automatically get the previous cursor for infinite queries.
2193 * The result will also be used to determine the value of `hasPreviousPage`.
2194 */
2195 getPreviousPageParam?: PageParamFunction<DataType, PageParam>;
2196 /**
2197 * If specified, only keep this many pages in cache at once.
2198 * If additional pages are fetched, older pages in the other
2199 * direction will be dropped from the cache.
2200 */
2201 maxPages?: number;
2202 };
2203 type InfiniteData<DataType, PageParam> = {
2204 pages: Array<DataType>;
2205 pageParams: Array<PageParam>;
2206 };
2207 /**
2208 * Strings describing the query state at any given time.
2209 */
2210 declare enum QueryStatus {
2211 uninitialized = "uninitialized",
2212 pending = "pending",
2213 fulfilled = "fulfilled",
2214 rejected = "rejected"
2215 }
2216 type RequestStatusFlags = {
2217 status: QueryStatus.uninitialized;
2218 isUninitialized: true;
2219 isLoading: false;
2220 isSuccess: false;
2221 isError: false;
2222 } | {
2223 status: QueryStatus.pending;
2224 isUninitialized: false;
2225 isLoading: true;
2226 isSuccess: false;
2227 isError: false;
2228 } | {
2229 status: QueryStatus.fulfilled;
2230 isUninitialized: false;
2231 isLoading: false;
2232 isSuccess: true;
2233 isError: false;
2234 } | {
2235 status: QueryStatus.rejected;
2236 isUninitialized: false;
2237 isLoading: false;
2238 isSuccess: false;
2239 isError: true;
2240 };
2241 /**
2242 * @public
2243 */
2244 type SubscriptionOptions = {
2245 /**
2246 * How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).
2247 */
2248 pollingInterval?: number;
2249 /**
2250 * Defaults to 'false'. This setting allows you to control whether RTK Query will continue polling if the window is not focused.
2251 *
2252 * If pollingInterval is not set or set to 0, this **will not be evaluated** until pollingInterval is greater than 0.
2253 *
2254 * Note: requires [`setupListeners`](./setupListeners) to have been called.
2255 */
2256 skipPollingIfUnfocused?: boolean;
2257 /**
2258 * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.
2259 *
2260 * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
2261 *
2262 * Note: requires [`setupListeners`](./setupListeners) to have been called.
2263 */
2264 refetchOnReconnect?: boolean;
2265 /**
2266 * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.
2267 *
2268 * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
2269 *
2270 * Note: requires [`setupListeners`](./setupListeners) to have been called.
2271 */
2272 refetchOnFocus?: boolean;
2273 };
2274 type Subscribers = {
2275 [requestId: string]: SubscriptionOptions;
2276 };
2277 type QueryKeys<Definitions extends EndpointDefinitions> = {
2278 [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any> ? K : never;
2279 }[keyof Definitions];
2280 type InfiniteQueryKeys<Definitions extends EndpointDefinitions> = {
2281 [K in keyof Definitions]: Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? K : never;
2282 }[keyof Definitions];
2283 type MutationKeys<Definitions extends EndpointDefinitions> = {
2284 [K in keyof Definitions]: Definitions[K] extends MutationDefinition<any, any, any, any> ? K : never;
2285 }[keyof Definitions];
2286 type BaseQuerySubState<D extends BaseEndpointDefinition<any, any, any>, DataType = ResultTypeFrom<D>> = {
2287 /**
2288 * The argument originally passed into the hook or `initiate` action call
2289 */
2290 originalArgs: QueryArgFromAnyQuery<D>;
2291 /**
2292 * A unique ID associated with the request
2293 */
2294 requestId: string;
2295 /**
2296 * The received data from the query
2297 */
2298 data?: DataType;
2299 /**
2300 * The received error if applicable
2301 */
2302 error?: SerializedError | (D extends QueryDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);
2303 /**
2304 * The name of the endpoint associated with the query
2305 */
2306 endpointName: string;
2307 /**
2308 * Time that the latest query started
2309 */
2310 startedTimeStamp: number;
2311 /**
2312 * Time that the latest query was fulfilled
2313 */
2314 fulfilledTimeStamp?: number;
2315 };
2316 type QuerySubState<D extends BaseEndpointDefinition<any, any, any>, DataType = ResultTypeFrom<D>> = Id<({
2317 status: QueryStatus.fulfilled;
2318 } & WithRequiredProp<BaseQuerySubState<D, DataType>, 'data' | 'fulfilledTimeStamp'> & {
2319 error: undefined;
2320 }) | ({
2321 status: QueryStatus.pending;
2322 } & BaseQuerySubState<D, DataType>) | ({
2323 status: QueryStatus.rejected;
2324 } & WithRequiredProp<BaseQuerySubState<D, DataType>, 'error'>) | {
2325 status: QueryStatus.uninitialized;
2326 originalArgs?: undefined;
2327 data?: undefined;
2328 error?: undefined;
2329 requestId?: undefined;
2330 endpointName?: string;
2331 startedTimeStamp?: undefined;
2332 fulfilledTimeStamp?: undefined;
2333 }>;
2334 type InfiniteQueryDirection = 'forward' | 'backward';
2335 type InfiniteQuerySubState<D extends BaseEndpointDefinition<any, any, any>> = D extends InfiniteQueryDefinition<any, any, any, any, any> ? QuerySubState<D, InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>> & {
2336 direction?: InfiniteQueryDirection;
2337 } : never;
2338 type BaseMutationSubState<D extends BaseEndpointDefinition<any, any, any>> = {
2339 requestId: string;
2340 data?: ResultTypeFrom<D>;
2341 error?: SerializedError | (D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);
2342 endpointName: string;
2343 startedTimeStamp: number;
2344 fulfilledTimeStamp?: number;
2345 };
2346 type MutationSubState<D extends BaseEndpointDefinition<any, any, any>> = (({
2347 status: QueryStatus.fulfilled;
2348 } & WithRequiredProp<BaseMutationSubState<D>, 'data' | 'fulfilledTimeStamp'>) & {
2349 error: undefined;
2350 }) | (({
2351 status: QueryStatus.pending;
2352 } & BaseMutationSubState<D>) & {
2353 data?: undefined;
2354 }) | ({
2355 status: QueryStatus.rejected;
2356 } & WithRequiredProp<BaseMutationSubState<D>, 'error'>) | {
2357 requestId?: undefined;
2358 status: QueryStatus.uninitialized;
2359 data?: undefined;
2360 error?: undefined;
2361 endpointName?: string;
2362 startedTimeStamp?: undefined;
2363 fulfilledTimeStamp?: undefined;
2364 };
2365 type CombinedState<D extends EndpointDefinitions, E extends string, ReducerPath extends string> = {
2366 queries: QueryState<D>;
2367 mutations: MutationState<D>;
2368 provided: InvalidationState<E>;
2369 subscriptions: SubscriptionState;
2370 config: ConfigState<ReducerPath>;
2371 };
2372 type InvalidationState<TagTypes extends string> = {
2373 [_ in TagTypes]: {
2374 [id: string]: Array<QueryCacheKey>;
2375 [id: number]: Array<QueryCacheKey>;
2376 };
2377 };
2378 type QueryState<D extends EndpointDefinitions> = {
2379 [queryCacheKey: string]: QuerySubState<D[string]> | InfiniteQuerySubState<D[string]> | undefined;
2380 };
2381 type SubscriptionState = {
2382 [queryCacheKey: string]: Subscribers | undefined;
2383 };
2384 type ConfigState<ReducerPath> = RefetchConfigOptions & {
2385 reducerPath: ReducerPath;
2386 online: boolean;
2387 focused: boolean;
2388 middlewareRegistered: boolean | 'conflict';
2389 } & ModifiableConfigState;
2390 type ModifiableConfigState = {
2391 keepUnusedDataFor: number;
2392 invalidationBehavior: 'delayed' | 'immediately';
2393 } & RefetchConfigOptions;
2394 type MutationState<D extends EndpointDefinitions> = {
2395 [requestId: string]: MutationSubState<D[string]> | undefined;
2396 };
2397 type RootState<Definitions extends EndpointDefinitions, TagTypes extends string, ReducerPath extends string> = {
2398 [P in ReducerPath]: CombinedState<Definitions, TagTypes, P>;
2399 };
2400
2401 type ResponseHandler = 'content-type' | 'json' | 'text' | ((response: Response) => Promise<any>);
2402 type CustomRequestInit = Override<RequestInit, {
2403 headers?: Headers | string[][] | Record<string, string | undefined> | undefined;
2404 }>;
2405 interface FetchArgs extends CustomRequestInit {
2406 url: string;
2407 params?: Record<string, any>;
2408 body?: any;
2409 responseHandler?: ResponseHandler;
2410 validateStatus?: (response: Response, body: any) => boolean;
2411 /**
2412 * A number in milliseconds that represents that maximum time a request can take before timing out.
2413 */
2414 timeout?: number;
2415 }
2416 type FetchBaseQueryError = {
2417 /**
2418 * * `number`:
2419 * HTTP status code
2420 */
2421 status: number;
2422 data: unknown;
2423 } | {
2424 /**
2425 * * `"FETCH_ERROR"`:
2426 * An error that occurred during execution of `fetch` or the `fetchFn` callback option
2427 **/
2428 status: 'FETCH_ERROR';
2429 data?: undefined;
2430 error: string;
2431 } | {
2432 /**
2433 * * `"PARSING_ERROR"`:
2434 * An error happened during parsing.
2435 * Most likely a non-JSON-response was returned with the default `responseHandler` "JSON",
2436 * or an error occurred while executing a custom `responseHandler`.
2437 **/
2438 status: 'PARSING_ERROR';
2439 originalStatus: number;
2440 data: string;
2441 error: string;
2442 } | {
2443 /**
2444 * * `"TIMEOUT_ERROR"`:
2445 * Request timed out
2446 **/
2447 status: 'TIMEOUT_ERROR';
2448 data?: undefined;
2449 error: string;
2450 } | {
2451 /**
2452 * * `"CUSTOM_ERROR"`:
2453 * A custom error type that you can return from your `queryFn` where another error might not make sense.
2454 **/
2455 status: 'CUSTOM_ERROR';
2456 data?: unknown;
2457 error: string;
2458 };
2459 type FetchBaseQueryArgs = {
2460 baseUrl?: string;
2461 prepareHeaders?: (headers: Headers, api: Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type' | 'forced'> & {
2462 arg: string | FetchArgs;
2463 extraOptions: unknown;
2464 }) => MaybePromise<Headers | void>;
2465 fetchFn?: (input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>;
2466 paramsSerializer?: (params: Record<string, any>) => string;
2467 /**
2468 * By default, we only check for 'application/json' and 'application/vnd.api+json' as the content-types for json. If you need to support another format, you can pass
2469 * in a predicate function for your given api to get the same automatic stringifying behavior
2470 * @example
2471 * ```ts
2472 * const isJsonContentType = (headers: Headers) => ["application/vnd.api+json", "application/json", "application/vnd.hal+json"].includes(headers.get("content-type")?.trim());
2473 * ```
2474 */
2475 isJsonContentType?: (headers: Headers) => boolean;
2476 /**
2477 * Defaults to `application/json`;
2478 */
2479 jsonContentType?: string;
2480 /**
2481 * Custom replacer function used when calling `JSON.stringify()`;
2482 */
2483 jsonReplacer?: (this: any, key: string, value: any) => any;
2484 } & RequestInit & Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>;
2485 type FetchBaseQueryMeta = {
2486 request: Request;
2487 response?: Response;
2488 };
2489 /**
2490 * This is a very small wrapper around fetch that aims to simplify requests.
2491 *
2492 * @example
2493 * ```ts
2494 * const baseQuery = fetchBaseQuery({
2495 * baseUrl: 'https://api.your-really-great-app.com/v1/',
2496 * prepareHeaders: (headers, { getState }) => {
2497 * const token = (getState() as RootState).auth.token;
2498 * // If we have a token set in state, let's assume that we should be passing it.
2499 * if (token) {
2500 * headers.set('authorization', `Bearer ${token}`);
2501 * }
2502 * return headers;
2503 * },
2504 * })
2505 * ```
2506 *
2507 * @param {string} baseUrl
2508 * The base URL for an API service.
2509 * Typically in the format of https://example.com/
2510 *
2511 * @param {(headers: Headers, api: { getState: () => unknown; arg: string | FetchArgs; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders
2512 * An optional function that can be used to inject headers on requests.
2513 * Provides a Headers object, most of the `BaseQueryApi` (`dispatch` is not available), and the arg passed into the query function.
2514 * Useful for setting authentication or headers that need to be set conditionally.
2515 *
2516 * @link https://developer.mozilla.org/en-US/docs/Web/API/Headers
2517 *
2518 * @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn
2519 * Accepts a custom `fetch` function if you do not want to use the default on the window.
2520 * Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`
2521 *
2522 * @param {(params: Record<string, unknown>) => string} paramsSerializer
2523 * An optional function that can be used to stringify querystring parameters.
2524 *
2525 * @param {(headers: Headers) => boolean} isJsonContentType
2526 * An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`
2527 *
2528 * @param {string} jsonContentType Used when automatically setting the content-type header for a request with a jsonifiable body that does not have an explicit content-type header. Defaults to `application/json`.
2529 *
2530 * @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.
2531 *
2532 * @param {number} timeout
2533 * A number in milliseconds that represents the maximum time a request can take before timing out.
2534 */
2535 declare function fetchBaseQuery({ baseUrl, prepareHeaders, fetchFn, paramsSerializer, isJsonContentType, jsonContentType, jsonReplacer, timeout: defaultTimeout, responseHandler: globalResponseHandler, validateStatus: globalValidateStatus, ...baseFetchOptions }?: FetchBaseQueryArgs): BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;
2536
2537 type RetryConditionFunction = (error: BaseQueryError<BaseQueryFn>, args: BaseQueryArg<BaseQueryFn>, extraArgs: {
2538 attempt: number;
2539 baseQueryApi: BaseQueryApi;
2540 extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions;
2541 }) => boolean;
2542 type RetryOptions = {
2543 /**
2544 * Function used to determine delay between retries
2545 */
2546 backoff?: (attempt: number, maxRetries: number) => Promise<void>;
2547 } & ({
2548 /**
2549 * How many times the query will be retried (default: 5)
2550 */
2551 maxRetries?: number;
2552 retryCondition?: undefined;
2553 } | {
2554 /**
2555 * Callback to determine if a retry should be attempted.
2556 * Return `true` for another retry and `false` to quit trying prematurely.
2557 */
2558 retryCondition?: RetryConditionFunction;
2559 maxRetries?: undefined;
2560 });
2561 declare function fail<BaseQuery extends BaseQueryFn = BaseQueryFn>(error: BaseQueryError<BaseQuery>, meta?: BaseQueryMeta<BaseQuery>): never;
2562 /**
2563 * A utility that can wrap `baseQuery` in the API definition to provide retries with a basic exponential backoff.
2564 *
2565 * @example
2566 *
2567 * ```ts
2568 * // codeblock-meta title="Retry every request 5 times by default"
2569 * import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'
2570 * interface Post {
2571 * id: number
2572 * name: string
2573 * }
2574 * type PostsResponse = Post[]
2575 *
2576 * // maxRetries: 5 is the default, and can be omitted. Shown for documentation purposes.
2577 * const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), { maxRetries: 5 });
2578 * export const api = createApi({
2579 * baseQuery: staggeredBaseQuery,
2580 * endpoints: (build) => ({
2581 * getPosts: build.query<PostsResponse, void>({
2582 * query: () => ({ url: 'posts' }),
2583 * }),
2584 * getPost: build.query<PostsResponse, string>({
2585 * query: (id) => ({ url: `post/${id}` }),
2586 * extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint
2587 * }),
2588 * }),
2589 * });
2590 *
2591 * export const { useGetPostsQuery, useGetPostQuery } = api;
2592 * ```
2593 */
2594 declare const retry: BaseQueryEnhancer<unknown, RetryOptions, void | RetryOptions> & {
2595 fail: typeof fail;
2596 };
2597
2598 declare function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T;
2599
2600 export { type Api, type ApiContext, type ApiEndpointInfiniteQuery, type ApiEndpointMutation, type ApiEndpointQuery, type ApiModules, type BaseEndpointDefinition, type BaseQueryApi, type BaseQueryArg, type BaseQueryEnhancer, type BaseQueryError, type BaseQueryExtraOptions, type BaseQueryFn, type BaseQueryMeta, type BaseQueryResult, type CombinedState, type CoreModule, type CreateApi, type CreateApiOptions, DefinitionType, type DefinitionsFromApi, type EndpointBuilder, type EndpointDefinition, type EndpointDefinitions, type FetchArgs, type FetchBaseQueryArgs, type FetchBaseQueryError, type FetchBaseQueryMeta, type InfiniteData, type InfiniteQueryActionCreatorResult, type InfiniteQueryArgFrom, type InfiniteQueryConfigOptions, type InfiniteQueryDefinition, type InfiniteQueryExtraOptions, type InfiniteQueryResultSelectorResult, type InfiniteQuerySubState, type Module, type MutationActionCreatorResult, type MutationDefinition, type MutationExtraOptions, type MutationResultSelectorResult, type OverrideResultType, type PageParamFrom, type PrefetchOptions, type QueryActionCreatorResult, type QueryArgFrom, type QueryCacheKey, type QueryDefinition, type QueryExtraOptions, type QueryKeys, type QueryResultSelectorResult, type QueryReturnValue, QueryStatus, type QuerySubState, type ResultDescription, type ResultTypeFrom, type RetryOptions, type RootState, type SerializeQueryArgs, type SkipToken, type StartQueryActionCreatorOptions, type SubscriptionOptions, type Id as TSHelpersId, type NoInfer as TSHelpersNoInfer, type Override as TSHelpersOverride, type TagDescription, type TagTypesFromApi, type TypedMutationOnQueryStarted, type TypedQueryOnQueryStarted, type UpdateDefinitions, buildCreateApi, copyWithStructuralSharing, coreModule, createApi, defaultSerializeQueryArgs, fakeBaseQuery, fetchBaseQuery, retry, setupListeners };