source: node_modules/@reduxjs/toolkit/dist/query/index.d.mts

Last change on this file was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago

Added visualizations

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