createApi.d.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. import type { Api, Module, ModuleName } from './apiTypes';
  2. import type { CombinedState } from './core/apiState';
  3. import type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes';
  4. import type { SerializeQueryArgs } from './defaultSerializeQueryArgs';
  5. import type { EndpointBuilder, EndpointDefinitions } from './endpointDefinitions';
  6. import type { AnyAction } from '@reduxjs/toolkit';
  7. import type { NoInfer } from './tsHelpers';
  8. export interface CreateApiOptions<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never> {
  9. /**
  10. * 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.
  11. *
  12. * @example
  13. *
  14. * ```ts
  15. * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
  16. *
  17. * const api = createApi({
  18. * // highlight-start
  19. * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  20. * // highlight-end
  21. * endpoints: (build) => ({
  22. * // ...endpoints
  23. * }),
  24. * })
  25. * ```
  26. */
  27. baseQuery: BaseQuery;
  28. /**
  29. * 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).
  30. *
  31. * @example
  32. *
  33. * ```ts
  34. * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
  35. *
  36. * const api = createApi({
  37. * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  38. * // highlight-start
  39. * tagTypes: ['Post', 'User'],
  40. * // highlight-end
  41. * endpoints: (build) => ({
  42. * // ...endpoints
  43. * }),
  44. * })
  45. * ```
  46. */
  47. tagTypes?: readonly TagTypes[];
  48. /**
  49. * 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'`.
  50. *
  51. * @example
  52. *
  53. * ```ts
  54. * // codeblock-meta title="apis.js"
  55. * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';
  56. *
  57. * const apiOne = createApi({
  58. * // highlight-start
  59. * reducerPath: 'apiOne',
  60. * // highlight-end
  61. * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  62. * endpoints: (builder) => ({
  63. * // ...endpoints
  64. * }),
  65. * });
  66. *
  67. * const apiTwo = createApi({
  68. * // highlight-start
  69. * reducerPath: 'apiTwo',
  70. * // highlight-end
  71. * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  72. * endpoints: (builder) => ({
  73. * // ...endpoints
  74. * }),
  75. * });
  76. * ```
  77. */
  78. reducerPath?: ReducerPath;
  79. /**
  80. * Accepts a custom function if you have a need to change the creation of cache keys for any reason.
  81. */
  82. serializeQueryArgs?: SerializeQueryArgs<BaseQueryArg<BaseQuery>>;
  83. /**
  84. * Endpoints are just a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are two basic endpoint types: [`query`](../../rtk-query/usage/queries) and [`mutation`](../../rtk-query/usage/mutations).
  85. */
  86. endpoints(build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>): Definitions;
  87. /**
  88. * 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.
  89. *
  90. * ```ts
  91. * // codeblock-meta title="keepUnusedDataFor example"
  92. *
  93. * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
  94. * interface Post {
  95. * id: number
  96. * name: string
  97. * }
  98. * type PostsResponse = Post[]
  99. *
  100. * const api = createApi({
  101. * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  102. * endpoints: (build) => ({
  103. * getPosts: build.query<PostsResponse, void>({
  104. * query: () => 'posts',
  105. * // highlight-start
  106. * keepUnusedDataFor: 5
  107. * // highlight-end
  108. * })
  109. * })
  110. * })
  111. * ```
  112. */
  113. keepUnusedDataFor?: number;
  114. /**
  115. * 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.
  116. * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
  117. * - `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.
  118. * - `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.
  119. *
  120. * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
  121. */
  122. refetchOnMountOrArgChange?: boolean | number;
  123. /**
  124. * 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.
  125. *
  126. * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
  127. *
  128. * Note: requires [`setupListeners`](./setupListeners) to have been called.
  129. */
  130. refetchOnFocus?: boolean;
  131. /**
  132. * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.
  133. *
  134. * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
  135. *
  136. * Note: requires [`setupListeners`](./setupListeners) to have been called.
  137. */
  138. refetchOnReconnect?: boolean;
  139. /**
  140. * A function that is passed every dispatched action. If this returns something other than `undefined`,
  141. * that return value will be used to rehydrate fulfilled & errored queries.
  142. *
  143. * @example
  144. *
  145. * ```ts
  146. * // codeblock-meta title="next-redux-wrapper rehydration example"
  147. * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
  148. * import { HYDRATE } from 'next-redux-wrapper'
  149. *
  150. * export const api = createApi({
  151. * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  152. * // highlight-start
  153. * extractRehydrationInfo(action, { reducerPath }) {
  154. * if (action.type === HYDRATE) {
  155. * return action.payload[reducerPath]
  156. * }
  157. * },
  158. * // highlight-end
  159. * endpoints: (build) => ({
  160. * // omitted
  161. * }),
  162. * })
  163. * ```
  164. */
  165. extractRehydrationInfo?: (action: AnyAction, { reducerPath, }: {
  166. reducerPath: ReducerPath;
  167. }) => undefined | CombinedState<NoInfer<Definitions>, NoInfer<TagTypes>, NoInfer<ReducerPath>>;
  168. }
  169. export declare type CreateApi<Modules extends ModuleName> = {
  170. /**
  171. * Creates a service to use in your application. Contains only the basic redux logic (the core module).
  172. *
  173. * @link https://rtk-query-docs.netlify.app/api/createApi
  174. */
  175. <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>;
  176. };
  177. /**
  178. * Builds a `createApi` method based on the provided `modules`.
  179. *
  180. * @link https://rtk-query-docs.netlify.app/concepts/customizing-create-api
  181. *
  182. * @example
  183. * ```ts
  184. * const MyContext = React.createContext<ReactReduxContextValue>(null as any);
  185. * const customCreateApi = buildCreateApi(
  186. * coreModule(),
  187. * reactHooksModule({ useDispatch: createDispatchHook(MyContext) })
  188. * );
  189. * ```
  190. *
  191. * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints
  192. * @returns A `createApi` method using the provided `modules`.
  193. */
  194. export declare function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(...modules: Modules): CreateApi<Modules[number]['name']>;