import type { AnyAction, ThunkDispatch } from '@reduxjs/toolkit'; import type { SerializeQueryArgs } from './defaultSerializeQueryArgs'; import type { QuerySubState, RootState } from './core/apiState'; import type { BaseQueryExtraOptions, BaseQueryFn, BaseQueryResult, BaseQueryArg, BaseQueryApi, QueryReturnValue, BaseQueryError, BaseQueryMeta } from './baseQueryTypes'; import type { HasRequiredProps, MaybePromise, OmitFromUnion, CastAny } from './tsHelpers'; import type { NEVER } from './fakeBaseQuery'; declare const resultType: unique symbol; declare const baseQuery: unique symbol; interface EndpointDefinitionWithQuery { /** * `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. * * @example * * ```ts * // codeblock-meta title="query example" * * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' * interface Post { * id: number * name: string * } * type PostsResponse = Post[] * * const api = createApi({ * baseQuery: fetchBaseQuery({ baseUrl: '/' }), * tagTypes: ['Post'], * endpoints: (build) => ({ * getPosts: build.query({ * // highlight-start * query: () => 'posts', * // highlight-end * }), * addPost: build.mutation>({ * // highlight-start * query: (body) => ({ * url: `posts`, * method: 'POST', * body, * }), * // highlight-end * invalidatesTags: [{ type: 'Post', id: 'LIST' }], * }), * }) * }) * ``` */ query(arg: QueryArg): BaseQueryArg; queryFn?: never; /** * A function to manipulate the data returned by a query or mutation. */ transformResponse?(baseQueryReturnValue: BaseQueryResult, meta: BaseQueryMeta, arg: QueryArg): ResultType | Promise; /** * A function to manipulate the data returned by a failed query or mutation. */ transformErrorResponse?(baseQueryReturnValue: BaseQueryError, meta: BaseQueryMeta, arg: QueryArg): unknown; /** * Defaults to `true`. * * Most apps should leave this setting on. The only time it can be a performance issue * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and * you're unable to paginate it. * * For details of how this works, please see the below. When it is set to `false`, * every request will cause subscribed components to rerender, even when the data has not changed. * * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing */ structuralSharing?: boolean; } interface EndpointDefinitionWithQueryFn { /** * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint. * * @example * ```ts * // codeblock-meta title="Basic queryFn example" * * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' * interface Post { * id: number * name: string * } * type PostsResponse = Post[] * * const api = createApi({ * baseQuery: fetchBaseQuery({ baseUrl: '/' }), * endpoints: (build) => ({ * getPosts: build.query({ * query: () => 'posts', * }), * flipCoin: build.query<'heads' | 'tails', void>({ * // highlight-start * queryFn(arg, queryApi, extraOptions, baseQuery) { * const randomVal = Math.random() * if (randomVal < 0.45) { * return { data: 'heads' } * } * if (randomVal < 0.9) { * return { data: 'tails' } * } * return { error: { status: 500, statusText: 'Internal Server Error', data: "Coin landed on it's edge!" } } * } * // highlight-end * }) * }) * }) * ``` */ queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions, baseQuery: (arg: Parameters[0]) => ReturnType): MaybePromise>>; query?: never; transformResponse?: never; transformErrorResponse?: never; /** * Defaults to `true`. * * Most apps should leave this setting on. The only time it can be a performance issue * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and * you're unable to paginate it. * * For details of how this works, please see the below. When it is set to `false`, * every request will cause subscribed components to rerender, even when the data has not changed. * * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing */ structuralSharing?: boolean; } export interface BaseEndpointTypes { QueryArg: QueryArg; BaseQuery: BaseQuery; ResultType: ResultType; } export declare type BaseEndpointDefinition = (([CastAny, {}>] extends [NEVER] ? never : EndpointDefinitionWithQuery) | EndpointDefinitionWithQueryFn) & { [resultType]?: ResultType; [baseQuery]?: BaseQuery; } & HasRequiredProps, { extraOptions: BaseQueryExtraOptions; }, { extraOptions?: BaseQueryExtraOptions; }>; export declare enum DefinitionType { query = "query", mutation = "mutation" } export declare type GetResultDescriptionFn = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => ReadonlyArray>; export declare type FullTagDescription = { type: TagType; id?: number | string; }; export declare type TagDescription = TagType | FullTagDescription; export declare type ResultDescription = ReadonlyArray> | GetResultDescriptionFn; /** @deprecated please use `onQueryStarted` instead */ export interface QueryApi { /** @deprecated please use `onQueryStarted` instead */ dispatch: ThunkDispatch; /** @deprecated please use `onQueryStarted` instead */ getState(): RootState; /** @deprecated please use `onQueryStarted` instead */ extra: unknown; /** @deprecated please use `onQueryStarted` instead */ requestId: string; /** @deprecated please use `onQueryStarted` instead */ context: Context; } export interface QueryTypes extends BaseEndpointTypes { /** * The endpoint definition type. To be used with some internal generic types. * @example * ```ts * const useMyWrappedHook: UseQuery = ... * ``` */ QueryDefinition: QueryDefinition; TagTypes: TagTypes; ReducerPath: ReducerPath; } export interface QueryExtraOptions { type: DefinitionType.query; /** * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query. * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array. * 1. `['Post']` - equivalent to `2` * 2. `[{ type: 'Post' }]` - equivalent to `1` * 3. `[{ type: 'Post', id: 1 }]` * 4. `(result, error, arg) => ['Post']` - equivalent to `5` * 5. `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4` * 6. `(result, error, arg) => [{ type: 'Post', id: 1 }]` * * @example * * ```ts * // codeblock-meta title="providesTags example" * * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' * interface Post { * id: number * name: string * } * type PostsResponse = Post[] * * const api = createApi({ * baseQuery: fetchBaseQuery({ baseUrl: '/' }), * tagTypes: ['Posts'], * endpoints: (build) => ({ * getPosts: build.query({ * query: () => 'posts', * // highlight-start * providesTags: (result) => * result * ? [ * ...result.map(({ id }) => ({ type: 'Posts' as const, id })), * { type: 'Posts', id: 'LIST' }, * ] * : [{ type: 'Posts', id: 'LIST' }], * // highlight-end * }) * }) * }) * ``` */ providesTags?: ResultDescription, BaseQueryMeta>; /** * Not to be used. A query should not invalidate tags in the cache. */ invalidatesTags?: never; /** * Can be provided to return a custom cache key value based on the query arguments. * * 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. * * 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. * * * @example * * ```ts * // codeblock-meta title="serializeQueryArgs : exclude value" * * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react' * interface Post { * id: number * name: string * } * * interface MyApiClient { * fetchPost: (id: string) => Promise * } * * createApi({ * baseQuery: fetchBaseQuery({ baseUrl: '/' }), * endpoints: (build) => ({ * // Example: an endpoint with an API client passed in as an argument, * // but only the item ID should be used as the cache key * getPost: build.query({ * queryFn: async ({ id, client }) => { * const post = await client.fetchPost(id) * return { data: post } * }, * // highlight-start * serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => { * const { id } = queryArgs * // This can return a string, an object, a number, or a boolean. * // If it returns an object, number or boolean, that value * // will be serialized automatically via `defaultSerializeQueryArgs` * return { id } // omit `client` from the cache key * * // Alternately, you can use `defaultSerializeQueryArgs` yourself: * // return defaultSerializeQueryArgs({ * // endpointName, * // queryArgs: { id }, * // endpointDefinition * // }) * // Or create and return a string yourself: * // return `getPost(${id})` * }, * // highlight-end * }), * }), *}) * ``` */ serializeQueryArgs?: SerializeQueryArgs>; /** * Can be provided to merge an incoming response value into the current cache data. * If supplied, no automatic structural sharing will be applied - it's up to * you to update the cache appropriately. * * Since RTKQ normally replaces cache entries with the new response, you will usually * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep * an existing cache entry so that it can be updated. * * Since this is wrapped with Immer, you , you may either mutate the `currentCacheValue` directly, * or return a new value, but _not_ both at once. * * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response, * the cache entry will just save the response data directly. * * Useful if you don't want a new request to completely override the current cache value, * maybe because you have manually updated it from another source and don't want those * updates to get lost. * * * @example * * ```ts * // codeblock-meta title="merge: pagination" * * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react' * interface Post { * id: number * name: string * } * * createApi({ * baseQuery: fetchBaseQuery({ baseUrl: '/' }), * endpoints: (build) => ({ * listItems: build.query({ * query: (pageNumber) => `/listItems?page=${pageNumber}`, * // Only have one cache entry because the arg always maps to one string * serializeQueryArgs: ({ endpointName }) => { * return endpointName * }, * // Always merge incoming data to the cache entry * merge: (currentCache, newItems) => { * currentCache.push(...newItems) * }, * // Refetch when the page arg changes * forceRefetch({ currentArg, previousArg }) { * return currentArg !== previousArg * }, * }), * }), *}) * ``` */ merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: { arg: QueryArg; baseQueryMeta: BaseQueryMeta; requestId: string; fulfilledTimeStamp: number; }): ResultType | void; /** * Check to see if the endpoint should force a refetch in cases where it normally wouldn't. * This is primarily useful for "infinite scroll" / pagination use cases where * RTKQ is keeping a single cache entry that is added to over time, in combination * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback * set to add incoming data to the cache entry each time. * * @example * * ```ts * // codeblock-meta title="forceRefresh: pagination" * * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react' * interface Post { * id: number * name: string * } * * createApi({ * baseQuery: fetchBaseQuery({ baseUrl: '/' }), * endpoints: (build) => ({ * listItems: build.query({ * query: (pageNumber) => `/listItems?page=${pageNumber}`, * // Only have one cache entry because the arg always maps to one string * serializeQueryArgs: ({ endpointName }) => { * return endpointName * }, * // Always merge incoming data to the cache entry * merge: (currentCache, newItems) => { * currentCache.push(...newItems) * }, * // Refetch when the page arg changes * forceRefetch({ currentArg, previousArg }) { * return currentArg !== previousArg * }, * }), * }), *}) * ``` */ forceRefetch?(params: { currentArg: QueryArg | undefined; previousArg: QueryArg | undefined; state: RootState; endpointState?: QuerySubState; }): boolean; /** * All of these are `undefined` at runtime, purely to be used in TypeScript declarations! */ Types?: QueryTypes; } export declare type QueryDefinition = BaseEndpointDefinition & QueryExtraOptions; export interface MutationTypes extends BaseEndpointTypes { /** * The endpoint definition type. To be used with some internal generic types. * @example * ```ts * const useMyWrappedHook: UseMutation = ... * ``` */ MutationDefinition: MutationDefinition; TagTypes: TagTypes; ReducerPath: ReducerPath; } export interface MutationExtraOptions { type: DefinitionType.mutation; /** * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache. * Expects the same shapes as `providesTags`. * * @example * * ```ts * // codeblock-meta title="invalidatesTags example" * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' * interface Post { * id: number * name: string * } * type PostsResponse = Post[] * * const api = createApi({ * baseQuery: fetchBaseQuery({ baseUrl: '/' }), * tagTypes: ['Posts'], * endpoints: (build) => ({ * getPosts: build.query({ * query: () => 'posts', * providesTags: (result) => * result * ? [ * ...result.map(({ id }) => ({ type: 'Posts' as const, id })), * { type: 'Posts', id: 'LIST' }, * ] * : [{ type: 'Posts', id: 'LIST' }], * }), * addPost: build.mutation>({ * query(body) { * return { * url: `posts`, * method: 'POST', * body, * } * }, * // highlight-start * invalidatesTags: [{ type: 'Posts', id: 'LIST' }], * // highlight-end * }), * }) * }) * ``` */ invalidatesTags?: ResultDescription, BaseQueryMeta>; /** * Not to be used. A mutation should not provide tags to the cache. */ providesTags?: never; /** * All of these are `undefined` at runtime, purely to be used in TypeScript declarations! */ Types?: MutationTypes; } export declare type MutationDefinition = BaseEndpointDefinition & MutationExtraOptions; export declare type EndpointDefinition = QueryDefinition | MutationDefinition; export declare type EndpointDefinitions = Record>; export declare function isQueryDefinition(e: EndpointDefinition): e is QueryDefinition; export declare function isMutationDefinition(e: EndpointDefinition): e is MutationDefinition; export declare type EndpointBuilder = { /** * An endpoint definition that retrieves data, and may provide tags to the cache. * * @example * ```js * // codeblock-meta title="Example of all query endpoint options" * const api = createApi({ * baseQuery, * endpoints: (build) => ({ * getPost: build.query({ * query: (id) => ({ url: `post/${id}` }), * // Pick out data and prevent nested properties in a hook or selector * transformResponse: (response) => response.data, * // Pick out error and prevent nested properties in a hook or selector * transformErrorResponse: (response) => response.error, * // `result` is the server response * providesTags: (result, error, id) => [{ type: 'Post', id }], * // trigger side effects or optimistic updates * onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {}, * // handle subscriptions etc * onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {}, * }), * }), *}); *``` */ query(definition: OmitFromUnion, 'type'>): QueryDefinition; /** * An endpoint definition that alters data on the server or will possibly invalidate the cache. * * @example * ```js * // codeblock-meta title="Example of all mutation endpoint options" * const api = createApi({ * baseQuery, * endpoints: (build) => ({ * updatePost: build.mutation({ * query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }), * // Pick out data and prevent nested properties in a hook or selector * transformResponse: (response) => response.data, * // Pick out error and prevent nested properties in a hook or selector * transformErrorResponse: (response) => response.error, * // `result` is the server response * invalidatesTags: (result, error, id) => [{ type: 'Post', id }], * // trigger side effects or optimistic updates * onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {}, * // handle subscriptions etc * onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {}, * }), * }), * }); * ``` */ mutation(definition: OmitFromUnion, 'type'>): MutationDefinition; }; export declare type AssertTagTypes = >(t: T) => T; export declare function calculateProvidedBy(description: ResultDescription | undefined, result: ResultType | undefined, error: ErrorType | undefined, queryArg: QueryArg, meta: MetaType | undefined, assertTagTypes: AssertTagTypes): readonly FullTagDescription[]; export declare function expandTagDescription(description: TagDescription): FullTagDescription; export declare type QueryArgFrom> = D extends BaseEndpointDefinition ? QA : unknown; export declare type ResultTypeFrom> = D extends BaseEndpointDefinition ? RT : unknown; export declare type ReducerPathFrom> = D extends EndpointDefinition ? RP : unknown; export declare type TagTypesFrom> = D extends EndpointDefinition ? RP : unknown; export declare type ReplaceTagTypes = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition ? QueryDefinition : Definitions[K] extends MutationDefinition ? MutationDefinition : never; }; export {};