@depup/reduxjs__toolkit 2.12.0-depup.28

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