@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,1009 @@
1
+ import * as _reduxjs_toolkit_query from '@reduxjs/toolkit/query';
2
+ import { QueryDefinition, TSHelpersId, TSHelpersOverride, QuerySubState, ResultTypeFrom, QueryStatus, QueryArgFrom, SkipToken, SubscriptionOptions, QueryActionCreatorResult, MutationDefinition, MutationResultSelectorResult, MutationActionCreatorResult, InfiniteQueryDefinition, InfiniteQuerySubState, PageParamFrom, InfiniteQueryArgFrom, InfiniteQueryActionCreatorResult, BaseQueryFn, EndpointDefinitions, DefinitionType, QueryKeys, PrefetchOptions, Module, Api, setupListeners } from '@reduxjs/toolkit/query';
3
+ export * from '@reduxjs/toolkit/query';
4
+ import * as react_redux from 'react-redux';
5
+ import { ReactReduxContextValue } from 'react-redux';
6
+ import { CreateSelectorFunction } from 'reselect';
7
+ import * as React from 'react';
8
+ import { Context } from 'react';
9
+
10
+ type InfiniteData<DataType, PageParam> = {
11
+ pages: Array<DataType>;
12
+ pageParams: Array<PageParam>;
13
+ };
14
+ type InfiniteQueryDirection = 'forward' | 'backward';
15
+
16
+ export declare const UNINITIALIZED_VALUE: unique symbol;
17
+ type UninitializedValue = typeof UNINITIALIZED_VALUE;
18
+
19
+ type QueryHooks<Definition extends QueryDefinition<any, any, any, any, any>> = {
20
+ useQuery: UseQuery<Definition>;
21
+ useLazyQuery: UseLazyQuery<Definition>;
22
+ useQuerySubscription: UseQuerySubscription<Definition>;
23
+ useLazyQuerySubscription: UseLazyQuerySubscription<Definition>;
24
+ useQueryState: UseQueryState<Definition>;
25
+ };
26
+ type InfiniteQueryHooks<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {
27
+ useInfiniteQuery: UseInfiniteQuery<Definition>;
28
+ useInfiniteQuerySubscription: UseInfiniteQuerySubscription<Definition>;
29
+ useInfiniteQueryState: UseInfiniteQueryState<Definition>;
30
+ };
31
+ type MutationHooks<Definition extends MutationDefinition<any, any, any, any, any>> = {
32
+ useMutation: UseMutation<Definition>;
33
+ };
34
+ /**
35
+ * A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
36
+ *
37
+ * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.
38
+ *
39
+ * This hook combines the functionality of both [`useQueryState`](#usequerystate) and [`useQuerySubscription`](#usequerysubscription) together, and is intended to be used in the majority of situations.
40
+ *
41
+ * #### Features
42
+ *
43
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
44
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
45
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
46
+ * - Returns the latest request status and cached data from the Redux store
47
+ * - Re-renders as the request status changes and data becomes available
48
+ */
49
+ type UseQuery<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions & UseQueryStateOptions<D, R>) => UseQueryHookResult<D, R>;
50
+ type TypedUseQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
51
+ type UseQueryHookResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>;
52
+ /**
53
+ * Helper type to manually type the result
54
+ * of the `useQuery` hook in userland code.
55
+ */
56
+ type TypedUseQueryHookResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> & TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>;
57
+ type UseQuerySubscriptionOptions = SubscriptionOptions & {
58
+ /**
59
+ * Prevents a query from automatically running.
60
+ *
61
+ * @remarks
62
+ * When `skip` is true (or `skipToken` is passed in as `arg`):
63
+ *
64
+ * - **If the query has cached data:**
65
+ * * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
66
+ * * The query will have a status of `uninitialized`
67
+ * * If `skip: false` is set after the initial load, the cached result will be used
68
+ * - **If the query does not have cached data:**
69
+ * * The query will have a status of `uninitialized`
70
+ * * The query will not exist in the state when viewed with the dev tools
71
+ * * The query will not automatically fetch on mount
72
+ * * The query will not automatically run when additional components with the same query are added that do run
73
+ *
74
+ * @example
75
+ * ```tsx
76
+ * // codeblock-meta no-transpile title="Skip example"
77
+ * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
78
+ * const { data, error, status } = useGetPokemonByNameQuery(name, {
79
+ * skip,
80
+ * });
81
+ *
82
+ * return (
83
+ * <div>
84
+ * {name} - {status}
85
+ * </div>
86
+ * );
87
+ * };
88
+ * ```
89
+ */
90
+ skip?: boolean;
91
+ /**
92
+ * 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.
93
+ * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
94
+ * - `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.
95
+ * - `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.
96
+ *
97
+ * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
98
+ */
99
+ refetchOnMountOrArgChange?: boolean | number;
100
+ };
101
+ /**
102
+ * Provides a way to reference the options accepted by the `useQuerySubscription`
103
+ * hook in userland code.
104
+ *
105
+ * Unlike other `Typed*` wrappers, this type has no generic parameters since
106
+ * {@linkcode UseQuerySubscriptionOptions} does not depend on a specific query
107
+ * definition.
108
+ *
109
+ * @since 2.11.3
110
+ * @public
111
+ */
112
+ type TypedUseQuerySubscriptionOptions = UseQuerySubscriptionOptions;
113
+ /**
114
+ * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.
115
+ *
116
+ * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.
117
+ *
118
+ * Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).
119
+ *
120
+ * #### Features
121
+ *
122
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
123
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
124
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
125
+ */
126
+ type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions) => UseQuerySubscriptionResult<D>;
127
+ type TypedUseQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
128
+ type UseQuerySubscriptionResult<D extends QueryDefinition<any, any, any, any>> = Pick<QueryActionCreatorResult<D>, 'refetch'>;
129
+ /**
130
+ * Helper type to manually type the result
131
+ * of the `useQuerySubscription` hook in userland code.
132
+ */
133
+ type TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscriptionResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
134
+ type UseLazyQueryLastPromiseInfo<D extends QueryDefinition<any, any, any, any>> = {
135
+ lastArg: QueryArgFrom<D>;
136
+ };
137
+ /**
138
+ * A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.
139
+ *
140
+ * This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).
141
+ *
142
+ * #### Features
143
+ *
144
+ * - Manual control over firing a request to retrieve data
145
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
146
+ * - Returns the latest request status and cached data from the Redux store
147
+ * - Re-renders as the request status changes and data becomes available
148
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
149
+ *
150
+ * #### Note
151
+ *
152
+ * When the trigger function returned from a LazyQuery is called, it always initiates a new request to the server even if there is cached data. Set `preferCacheValue`(the second argument to the function) as `true` if you want it to immediately return a cached value if one exists.
153
+ */
154
+ type UseLazyQuery<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(options?: SubscriptionOptions & Omit<UseQueryStateOptions<D, R>, 'skip'>) => [
155
+ LazyQueryTrigger<D>,
156
+ UseLazyQueryStateResult<D, R>,
157
+ UseLazyQueryLastPromiseInfo<D>
158
+ ];
159
+ type TypedUseLazyQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
160
+ type UseLazyQueryStateResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & {
161
+ /**
162
+ * Resets the hook state to its initial `uninitialized` state.
163
+ * This will also remove the last result from the cache.
164
+ */
165
+ reset: () => void;
166
+ };
167
+ /**
168
+ * Helper type to manually type the result
169
+ * of the `useLazyQuery` hook in userland code.
170
+ */
171
+ type TypedUseLazyQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseLazyQueryStateResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;
172
+ type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {
173
+ /**
174
+ * Triggers a lazy query.
175
+ *
176
+ * By default, this will start a new request even if there is already a value in the cache.
177
+ * If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.
178
+ *
179
+ * @remarks
180
+ * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
181
+ *
182
+ * @example
183
+ * ```ts
184
+ * // codeblock-meta title="Using .unwrap with async await"
185
+ * try {
186
+ * const payload = await getUserById(1).unwrap();
187
+ * console.log('fulfilled', payload);
188
+ * } catch (error) {
189
+ * console.error('rejected', error);
190
+ * }
191
+ * ```
192
+ */
193
+ (arg: QueryArgFrom<D>, preferCacheValue?: boolean): QueryActionCreatorResult<D>;
194
+ };
195
+ type TypedLazyQueryTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = LazyQueryTrigger<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
196
+ /**
197
+ * A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.
198
+ *
199
+ * Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).
200
+ *
201
+ * #### Features
202
+ *
203
+ * - Manual control over firing a request to retrieve data
204
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
205
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
206
+ */
207
+ type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (options?: SubscriptionOptions) => readonly [
208
+ LazyQueryTrigger<D>,
209
+ QueryArgFrom<D> | UninitializedValue,
210
+ {
211
+ reset: () => void;
212
+ }
213
+ ];
214
+ type TypedUseLazyQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
215
+ /**
216
+ * @internal
217
+ */
218
+ type QueryStateSelector<R extends Record<string, any>, D extends QueryDefinition<any, any, any, any>> = (state: UseQueryStateDefaultResult<D>) => R;
219
+ /**
220
+ * Provides a way to define a strongly-typed version of
221
+ * {@linkcode QueryStateSelector} for use with a specific query.
222
+ * This is useful for scenarios where you want to create a "pre-typed"
223
+ * {@linkcode UseQueryStateOptions.selectFromResult | selectFromResult}
224
+ * function.
225
+ *
226
+ * @example
227
+ * <caption>#### __Create a strongly-typed `selectFromResult` selector function__</caption>
228
+ *
229
+ * ```tsx
230
+ * import type { TypedQueryStateSelector } from '@reduxjs/toolkit/query/react';
231
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
232
+ *
233
+ * type Post = {
234
+ * id: number;
235
+ * title: string;
236
+ * };
237
+ *
238
+ * type PostsApiResponse = {
239
+ * posts: Post[];
240
+ * total: number;
241
+ * skip: number;
242
+ * limit: number;
243
+ * };
244
+ *
245
+ * type QueryArgument = number | undefined;
246
+ *
247
+ * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>;
248
+ *
249
+ * type SelectedResult = Pick<PostsApiResponse, 'posts'>;
250
+ *
251
+ * const postsApiSlice = createApi({
252
+ * baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),
253
+ * reducerPath: 'postsApi',
254
+ * tagTypes: ['Posts'],
255
+ * endpoints: (build) => ({
256
+ * getPosts: build.query<PostsApiResponse, QueryArgument>({
257
+ * query: (limit = 5) => `?limit=${limit}&select=title`,
258
+ * }),
259
+ * }),
260
+ * });
261
+ *
262
+ * const { useGetPostsQuery } = postsApiSlice;
263
+ *
264
+ * function PostById({ id }: { id: number }) {
265
+ * const { post } = useGetPostsQuery(undefined, {
266
+ * selectFromResult: (state) => ({
267
+ * post: state.data?.posts.find((post) => post.id === id),
268
+ * }),
269
+ * });
270
+ *
271
+ * return <li>{post?.title}</li>;
272
+ * }
273
+ *
274
+ * const EMPTY_ARRAY: Post[] = [];
275
+ *
276
+ * const typedSelectFromResult: TypedQueryStateSelector<
277
+ * PostsApiResponse,
278
+ * QueryArgument,
279
+ * BaseQueryFunction,
280
+ * SelectedResult
281
+ * > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY });
282
+ *
283
+ * function PostsList() {
284
+ * const { posts } = useGetPostsQuery(undefined, {
285
+ * selectFromResult: typedSelectFromResult,
286
+ * });
287
+ *
288
+ * return (
289
+ * <div>
290
+ * <ul>
291
+ * {posts.map((post) => (
292
+ * <PostById key={post.id} id={post.id} />
293
+ * ))}
294
+ * </ul>
295
+ * </div>
296
+ * );
297
+ * }
298
+ * ```
299
+ *
300
+ * @template ResultType - The type of the result `data` returned by the query.
301
+ * @template QueryArgumentType - The type of the argument passed into the query.
302
+ * @template BaseQueryFunctionType - The type of the base query function being used.
303
+ * @template SelectedResultType - The type of the selected result returned by the __`selectFromResult`__ function.
304
+ *
305
+ * @since 2.3.0
306
+ * @public
307
+ */
308
+ type TypedQueryStateSelector<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, SelectedResultType extends Record<string, any> = UseQueryStateDefaultResult<QueryDefinition<QueryArgumentType, BaseQueryFunctionType, string, ResultType, string>>> = QueryStateSelector<SelectedResultType, QueryDefinition<QueryArgumentType, BaseQueryFunctionType, string, ResultType, string>>;
309
+ /**
310
+ * A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
311
+ *
312
+ * Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).
313
+ *
314
+ * #### Features
315
+ *
316
+ * - Returns the latest request status and cached data from the Redux store
317
+ * - Re-renders as the request status changes and data becomes available
318
+ */
319
+ type UseQueryState<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(arg: QueryArgFrom<D> | SkipToken, options?: UseQueryStateOptions<D, R>) => UseQueryStateResult<D, R>;
320
+ type TypedUseQueryState<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQueryState<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
321
+ /**
322
+ * @internal
323
+ */
324
+ type UseQueryStateOptions<D extends QueryDefinition<any, any, any, any>, R extends Record<string, any>> = {
325
+ /**
326
+ * Prevents a query from automatically running.
327
+ *
328
+ * @remarks
329
+ * When skip is true:
330
+ *
331
+ * - **If the query has cached data:**
332
+ * * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
333
+ * * The query will have a status of `uninitialized`
334
+ * * If `skip: false` is set after skipping the initial load, the cached result will be used
335
+ * - **If the query does not have cached data:**
336
+ * * The query will have a status of `uninitialized`
337
+ * * The query will not exist in the state when viewed with the dev tools
338
+ * * The query will not automatically fetch on mount
339
+ * * The query will not automatically run when additional components with the same query are added that do run
340
+ *
341
+ * @example
342
+ * ```tsx
343
+ * // codeblock-meta title="Skip example"
344
+ * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
345
+ * const { data, error, status } = useGetPokemonByNameQuery(name, {
346
+ * skip,
347
+ * });
348
+ *
349
+ * return (
350
+ * <div>
351
+ * {name} - {status}
352
+ * </div>
353
+ * );
354
+ * };
355
+ * ```
356
+ */
357
+ skip?: boolean;
358
+ /**
359
+ * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.
360
+ * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.
361
+ * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
362
+ *
363
+ * @example
364
+ * ```tsx
365
+ * // codeblock-meta title="Using selectFromResult to extract a single result"
366
+ * function PostsList() {
367
+ * const { data: posts } = api.useGetPostsQuery();
368
+ *
369
+ * return (
370
+ * <ul>
371
+ * {posts?.data?.map((post) => (
372
+ * <PostById key={post.id} id={post.id} />
373
+ * ))}
374
+ * </ul>
375
+ * );
376
+ * }
377
+ *
378
+ * function PostById({ id }: { id: number }) {
379
+ * // Will select the post with the given id, and will only rerender if the given posts data changes
380
+ * const { post } = api.useGetPostsQuery(undefined, {
381
+ * selectFromResult: ({ data }) => ({
382
+ * post: data?.find((post) => post.id === id),
383
+ * }),
384
+ * });
385
+ *
386
+ * return <li>{post?.name}</li>;
387
+ * }
388
+ * ```
389
+ */
390
+ selectFromResult?: QueryStateSelector<R, D>;
391
+ };
392
+ /**
393
+ * Provides a way to define a "pre-typed" version of
394
+ * {@linkcode UseQueryStateOptions} with specific options for a given query.
395
+ * This is particularly useful for setting default query behaviors such as
396
+ * refetching strategies, which can be overridden as needed.
397
+ *
398
+ * @example
399
+ * <caption>#### __Create a `useQuery` hook with default options__</caption>
400
+ *
401
+ * ```ts
402
+ * import type {
403
+ * SubscriptionOptions,
404
+ * TypedUseQueryStateOptions,
405
+ * } from '@reduxjs/toolkit/query/react';
406
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
407
+ *
408
+ * type Post = {
409
+ * id: number;
410
+ * name: string;
411
+ * };
412
+ *
413
+ * const api = createApi({
414
+ * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
415
+ * tagTypes: ['Post'],
416
+ * endpoints: (build) => ({
417
+ * getPosts: build.query<Post[], void>({
418
+ * query: () => 'posts',
419
+ * }),
420
+ * }),
421
+ * });
422
+ *
423
+ * const { useGetPostsQuery } = api;
424
+ *
425
+ * export const useGetPostsQueryWithDefaults = <
426
+ * SelectedResult extends Record<string, any>,
427
+ * >(
428
+ * overrideOptions: TypedUseQueryStateOptions<
429
+ * Post[],
430
+ * void,
431
+ * ReturnType<typeof fetchBaseQuery>,
432
+ * SelectedResult
433
+ * > &
434
+ * SubscriptionOptions,
435
+ * ) =>
436
+ * useGetPostsQuery(undefined, {
437
+ * // Insert default options here
438
+ *
439
+ * refetchOnMountOrArgChange: true,
440
+ * refetchOnFocus: true,
441
+ * ...overrideOptions,
442
+ * });
443
+ * ```
444
+ *
445
+ * @template ResultType - The type of the result `data` returned by the query.
446
+ * @template QueryArg - The type of the argument passed into the query.
447
+ * @template BaseQuery - The type of the base query function being used.
448
+ * @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.
449
+ *
450
+ * @since 2.2.8
451
+ * @public
452
+ */
453
+ type TypedUseQueryStateOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, SelectedResult extends Record<string, any> = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseQueryStateOptions<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>, SelectedResult>;
454
+ type UseQueryStateResult<_ extends QueryDefinition<any, any, any, any>, R> = R;
455
+ /**
456
+ * Helper type to manually type the result
457
+ * of the `useQueryState` hook in userland code.
458
+ */
459
+ type TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = R;
460
+ type UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> = QuerySubState<D> & {
461
+ /**
462
+ * Where `data` tries to hold data as much as possible, also reusing
463
+ * data from the last arguments passed into the hook, this property
464
+ * will always contain the received data from the query, for the current query arguments.
465
+ */
466
+ currentData?: ResultTypeFrom<D>;
467
+ /**
468
+ * Query has not started yet.
469
+ */
470
+ isUninitialized: false;
471
+ /**
472
+ * Query is currently loading for the first time. No data yet.
473
+ */
474
+ isLoading: false;
475
+ /**
476
+ * Query is currently fetching, but might have data from an earlier request.
477
+ */
478
+ isFetching: false;
479
+ /**
480
+ * Query has data from a successful load.
481
+ */
482
+ isSuccess: false;
483
+ /**
484
+ * Query is currently in "error" state.
485
+ */
486
+ isError: false;
487
+ };
488
+ type UseQueryStateUninitialized<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<Extract<UseQueryStateBaseResult<D>, {
489
+ status: QueryStatus.uninitialized;
490
+ }>, {
491
+ isUninitialized: true;
492
+ }>;
493
+ type UseQueryStateLoading<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {
494
+ isLoading: true;
495
+ isFetching: boolean;
496
+ data: undefined;
497
+ }>;
498
+ type UseQueryStateSuccessFetching<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {
499
+ isSuccess: true;
500
+ isFetching: true;
501
+ error: undefined;
502
+ } & {
503
+ data: ResultTypeFrom<D>;
504
+ } & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>>;
505
+ type UseQueryStateSuccessNotFetching<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {
506
+ isSuccess: true;
507
+ isFetching: false;
508
+ error: undefined;
509
+ } & {
510
+ data: ResultTypeFrom<D>;
511
+ currentData: ResultTypeFrom<D>;
512
+ } & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>>;
513
+ type UseQueryStateError<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {
514
+ isError: true;
515
+ } & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>>;
516
+ type UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> = TSHelpersId<UseQueryStateUninitialized<D> | UseQueryStateLoading<D> | UseQueryStateSuccessFetching<D> | UseQueryStateSuccessNotFetching<D> | UseQueryStateError<D>> & {
517
+ /**
518
+ * @deprecated Included for completeness, but discouraged.
519
+ * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
520
+ * and `isUninitialized` flags instead
521
+ */
522
+ status: QueryStatus;
523
+ };
524
+ type LazyInfiniteQueryTrigger<D extends InfiniteQueryDefinition<any, any, any, any, any>> = {
525
+ /**
526
+ * Triggers a lazy query.
527
+ *
528
+ * By default, this will start a new request even if there is already a value in the cache.
529
+ * If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.
530
+ *
531
+ * @remarks
532
+ * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
533
+ *
534
+ * @example
535
+ * ```ts
536
+ * // codeblock-meta title="Using .unwrap with async await"
537
+ * try {
538
+ * const payload = await getUserById(1).unwrap();
539
+ * console.log('fulfilled', payload);
540
+ * } catch (error) {
541
+ * console.error('rejected', error);
542
+ * }
543
+ * ```
544
+ */
545
+ (arg: QueryArgFrom<D>, direction: InfiniteQueryDirection): InfiniteQueryActionCreatorResult<D>;
546
+ };
547
+ type TypedLazyInfiniteQueryTrigger<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = LazyInfiniteQueryTrigger<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
548
+ type UseInfiniteQuerySubscriptionOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>> = SubscriptionOptions & {
549
+ /**
550
+ * Prevents a query from automatically running.
551
+ *
552
+ * @remarks
553
+ * When `skip` is true (or `skipToken` is passed in as `arg`):
554
+ *
555
+ * - **If the query has cached data:**
556
+ * * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
557
+ * * The query will have a status of `uninitialized`
558
+ * * If `skip: false` is set after the initial load, the cached result will be used
559
+ * - **If the query does not have cached data:**
560
+ * * The query will have a status of `uninitialized`
561
+ * * The query will not exist in the state when viewed with the dev tools
562
+ * * The query will not automatically fetch on mount
563
+ * * The query will not automatically run when additional components with the same query are added that do run
564
+ *
565
+ * @example
566
+ * ```tsx
567
+ * // codeblock-meta no-transpile title="Skip example"
568
+ * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
569
+ * const { data, error, status } = useGetPokemonByNameQuery(name, {
570
+ * skip,
571
+ * });
572
+ *
573
+ * return (
574
+ * <div>
575
+ * {name} - {status}
576
+ * </div>
577
+ * );
578
+ * };
579
+ * ```
580
+ */
581
+ skip?: boolean;
582
+ /**
583
+ * 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.
584
+ * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
585
+ * - `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.
586
+ * - `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.
587
+ *
588
+ * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
589
+ */
590
+ refetchOnMountOrArgChange?: boolean | number;
591
+ initialPageParam?: PageParamFrom<D>;
592
+ /**
593
+ * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched
594
+ * (due to tag invalidation, polling, arg change configuration, or manual refetching),
595
+ * RTK Query will try to sequentially refetch all pages currently in the cache.
596
+ * When `false` only the first page will be refetched.
597
+ *
598
+ * This option applies to all automatic refetches for this subscription (polling, tag invalidation, etc.).
599
+ * It can be overridden on a per-call basis using the `refetch()` method.
600
+ */
601
+ refetchCachedPages?: boolean;
602
+ };
603
+ type TypedUseInfiniteQuerySubscription<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscription<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
604
+ type UseInfiniteQuerySubscriptionResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = {
605
+ refetch: (options?: Pick<UseInfiniteQuerySubscriptionOptions<D>, 'refetchCachedPages'>) => InfiniteQueryActionCreatorResult<D>;
606
+ trigger: LazyInfiniteQueryTrigger<D>;
607
+ fetchNextPage: () => InfiniteQueryActionCreatorResult<D>;
608
+ fetchPreviousPage: () => InfiniteQueryActionCreatorResult<D>;
609
+ };
610
+ /**
611
+ * Helper type to manually type the result
612
+ * of the `useQuerySubscription` hook in userland code.
613
+ */
614
+ type TypedUseInfiniteQuerySubscriptionResult<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscriptionResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
615
+ type InfiniteQueryStateSelector<R extends Record<string, any>, D extends InfiniteQueryDefinition<any, any, any, any, any>> = (state: UseInfiniteQueryStateDefaultResult<D>) => R;
616
+ type TypedInfiniteQueryStateSelector<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, SelectedResult extends Record<string, any> = UseInfiniteQueryStateDefaultResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>> = InfiniteQueryStateSelector<SelectedResult, InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
617
+ /**
618
+ * A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available. Additionally, it will cache multiple "pages" worth of responses within a single cache entry, and allows fetching more pages forwards and backwards from the current cached pages.
619
+ *
620
+ * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.
621
+ *
622
+ * The `data` field will be a `{pages: Data[], pageParams: PageParam[]}` structure containing all fetched page responses and the corresponding page param values for each page. You may use this to render individual pages, combine all pages into a single infinite list, or other display logic as needed.
623
+ *
624
+ * This hook combines the functionality of both [`useInfiniteQueryState`](#useinfinitequerystate) and [`useInfiniteQuerySubscription`](#useinfinitequerysubscription) together, and is intended to be used in the majority of situations.
625
+ *
626
+ * As with normal query hooks, `skipToken` is a valid argument that will skip the query from executing.
627
+ *
628
+ * By default, the initial request will use the `initialPageParam` value that was defined on the infinite query endpoint. If you want to start from a different value, you can pass `initialPageParam` as part of the hook options to override that initial request value.
629
+ *
630
+ * Use the returned `fetchNextPage` and `fetchPreviousPage` methods on the hook result object to trigger fetches forwards and backwards. These will always calculate the next or previous page param based on the current cached pages and the provided `getNext/PreviousPageParam` callbacks defined in the endpoint.
631
+ *
632
+ *
633
+ * #### Features
634
+ *
635
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
636
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
637
+ * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards
638
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
639
+ * - Returns the latest request status and cached data from the Redux store
640
+ * - Re-renders as the request status changes and data becomes available
641
+ */
642
+ type UseInfiniteQuery<D extends InfiniteQueryDefinition<any, any, any, any, any>> = <R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>>(arg: InfiniteQueryArgFrom<D> | SkipToken, options?: UseInfiniteQuerySubscriptionOptions<D> & UseInfiniteQueryStateOptions<D, R>) => UseInfiniteQueryHookResult<D, R> & Pick<UseInfiniteQuerySubscriptionResult<D>, 'fetchNextPage' | 'fetchPreviousPage'>;
643
+ type TypedUseInfiniteQuery<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuery<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
644
+ /**
645
+ * A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
646
+ *
647
+ * Note that this hook does not trigger fetching new data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQuerySubscription`](#useinfinitequerysubscription).
648
+ *
649
+ * #### Features
650
+ *
651
+ * - Returns the latest request status and cached data from the Redux store
652
+ * - Re-renders as the request status changes and data becomes available
653
+ */
654
+ type UseInfiniteQueryState<D extends InfiniteQueryDefinition<any, any, any, any, any>> = <R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>>(arg: InfiniteQueryArgFrom<D> | SkipToken, options?: UseInfiniteQueryStateOptions<D, R>) => UseInfiniteQueryStateResult<D, R>;
655
+ type TypedUseInfiniteQueryState<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQueryState<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
656
+ /**
657
+ * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data. Additionally, it will cache multiple "pages" worth of responses within a single cache entry, and allows fetching more pages forwards and backwards from the current cached pages.
658
+ *
659
+ * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.
660
+ *
661
+ * Note that this hook does not return a request status or cached data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQueryState`](#useinfinitequerystate).
662
+ *
663
+ * #### Features
664
+ *
665
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
666
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
667
+ * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards
668
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
669
+ */
670
+ type UseInfiniteQuerySubscription<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D> | SkipToken, options?: UseInfiniteQuerySubscriptionOptions<D>) => UseInfiniteQuerySubscriptionResult<D>;
671
+ type UseInfiniteQueryHookResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = UseInfiniteQueryStateResult<D, R> & Pick<UseInfiniteQuerySubscriptionResult<D>, 'refetch' | 'fetchNextPage' | 'fetchPreviousPage'>;
672
+ type TypedUseInfiniteQueryHookResult<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>> = UseInfiniteQueryHookResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>, R>;
673
+ type UseInfiniteQueryStateOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>, R extends Record<string, any>> = {
674
+ /**
675
+ * Prevents a query from automatically running.
676
+ *
677
+ * @remarks
678
+ * When skip is true:
679
+ *
680
+ * - **If the query has cached data:**
681
+ * * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
682
+ * * The query will have a status of `uninitialized`
683
+ * * If `skip: false` is set after skipping the initial load, the cached result will be used
684
+ * - **If the query does not have cached data:**
685
+ * * The query will have a status of `uninitialized`
686
+ * * The query will not exist in the state when viewed with the dev tools
687
+ * * The query will not automatically fetch on mount
688
+ * * The query will not automatically run when additional components with the same query are added that do run
689
+ *
690
+ * @example
691
+ * ```tsx
692
+ * // codeblock-meta title="Skip example"
693
+ * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
694
+ * const { data, error, status } = useGetPokemonByNameQuery(name, {
695
+ * skip,
696
+ * });
697
+ *
698
+ * return (
699
+ * <div>
700
+ * {name} - {status}
701
+ * </div>
702
+ * );
703
+ * };
704
+ * ```
705
+ */
706
+ skip?: boolean;
707
+ /**
708
+ * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.
709
+ * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.
710
+ * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
711
+ * Note that this should always return an object (not a primitive), as RTKQ adds fields to the return value.
712
+ *
713
+ * @example
714
+ * ```tsx
715
+ * // codeblock-meta title="Using selectFromResult to extract a single result"
716
+ * function PostsList() {
717
+ * const { data: posts } = api.useGetPostsQuery();
718
+ *
719
+ * return (
720
+ * <ul>
721
+ * {posts?.data?.map((post) => (
722
+ * <PostById key={post.id} id={post.id} />
723
+ * ))}
724
+ * </ul>
725
+ * );
726
+ * }
727
+ *
728
+ * function PostById({ id }: { id: number }) {
729
+ * // Will select the post with the given id, and will only rerender if the given posts data changes
730
+ * const { post } = api.useGetPostsQuery(undefined, {
731
+ * selectFromResult: ({ data }) => ({
732
+ * post: data?.find((post) => post.id === id),
733
+ * }),
734
+ * });
735
+ *
736
+ * return <li>{post?.name}</li>;
737
+ * }
738
+ * ```
739
+ */
740
+ selectFromResult?: InfiniteQueryStateSelector<R, D>;
741
+ };
742
+ type TypedUseInfiniteQueryStateOptions<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, SelectedResult extends Record<string, any> = UseInfiniteQueryStateDefaultResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>> = UseInfiniteQueryStateOptions<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>, SelectedResult>;
743
+ type UseInfiniteQueryStateResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = R;
744
+ type TypedUseInfiniteQueryStateResult<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, R = UseInfiniteQueryStateDefaultResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>> = UseInfiniteQueryStateResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>, R>;
745
+ type UseInfiniteQueryStateBaseResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = InfiniteQuerySubState<D> & {
746
+ /**
747
+ * Where `data` tries to hold data as much as possible, also reusing
748
+ * data from the last arguments passed into the hook, this property
749
+ * will always contain the received data from the query, for the current query arguments.
750
+ */
751
+ currentData?: InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>;
752
+ /**
753
+ * Query has not started yet.
754
+ */
755
+ isUninitialized: false;
756
+ /**
757
+ * Query is currently loading for the first time. No data yet.
758
+ */
759
+ isLoading: false;
760
+ /**
761
+ * Query is currently fetching, but might have data from an earlier request.
762
+ */
763
+ isFetching: false;
764
+ /**
765
+ * Query has data from a successful load.
766
+ */
767
+ isSuccess: false;
768
+ /**
769
+ * Query is currently in "error" state.
770
+ */
771
+ isError: false;
772
+ hasNextPage: boolean;
773
+ hasPreviousPage: boolean;
774
+ isFetchingNextPage: boolean;
775
+ isFetchingPreviousPage: boolean;
776
+ };
777
+ type UseInfiniteQueryStateDefaultResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = TSHelpersId<TSHelpersOverride<Extract<UseInfiniteQueryStateBaseResult<D>, {
778
+ status: QueryStatus.uninitialized;
779
+ }>, {
780
+ isUninitialized: true;
781
+ }> | TSHelpersOverride<UseInfiniteQueryStateBaseResult<D>, {
782
+ isLoading: true;
783
+ isFetching: boolean;
784
+ data: undefined;
785
+ } | ({
786
+ isSuccess: true;
787
+ isFetching: true;
788
+ error: undefined;
789
+ } & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp'>>) | ({
790
+ isSuccess: true;
791
+ isFetching: false;
792
+ error: undefined;
793
+ } & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp' | 'currentData'>>) | ({
794
+ isError: true;
795
+ } & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'error'>>)>> & {
796
+ /**
797
+ * @deprecated Included for completeness, but discouraged.
798
+ * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
799
+ * and `isUninitialized` flags instead
800
+ */
801
+ status: QueryStatus;
802
+ };
803
+ type MutationStateSelector<R extends Record<string, any>, D extends MutationDefinition<any, any, any, any>> = (state: MutationResultSelectorResult<D>) => R;
804
+ type UseMutationStateOptions<D extends MutationDefinition<any, any, any, any>, R extends Record<string, any>> = {
805
+ selectFromResult?: MutationStateSelector<R, D>;
806
+ fixedCacheKey?: string;
807
+ };
808
+ /**
809
+ * Provides a way to define a "pre-typed" version of
810
+ * {@linkcode UseMutationStateOptions} with specific options for a given mutation.
811
+ *
812
+ * @template ResultType - The type of the result `data` returned by the mutation.
813
+ * @template QueryArg - The type of the argument passed into the mutation.
814
+ * @template BaseQuery - The type of the base query function being used.
815
+ * @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.
816
+ *
817
+ * @since 2.11.3
818
+ * @public
819
+ */
820
+ type TypedUseMutationStateOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, SelectedResult extends Record<string, any> = MutationResultSelectorResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseMutationStateOptions<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>, SelectedResult>;
821
+ type UseMutationStateResult<D extends MutationDefinition<any, any, any, any>, R> = R & {
822
+ originalArgs?: QueryArgFrom<D>;
823
+ /**
824
+ * Resets the hook state to its initial `uninitialized` state.
825
+ * This will also remove the last result from the cache.
826
+ */
827
+ reset: () => void;
828
+ };
829
+ /**
830
+ * Helper type to manually type the result
831
+ * of the `useMutation` hook in userland code.
832
+ */
833
+ type TypedUseMutationResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = MutationResultSelectorResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseMutationStateResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;
834
+ /**
835
+ * A React hook that lets you trigger an update request for a given endpoint, and subscribes the component to read the request status from the Redux store. The component will re-render as the loading status changes.
836
+ *
837
+ * #### Features
838
+ *
839
+ * - Manual control over firing a request to alter data on the server or possibly invalidate the cache
840
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
841
+ * - Returns the latest request status and cached data from the Redux store
842
+ * - Re-renders as the request status changes and data becomes available
843
+ */
844
+ type UseMutation<D extends MutationDefinition<any, any, any, any>> = <R extends Record<string, any> = MutationResultSelectorResult<D>>(options?: UseMutationStateOptions<D, R>) => readonly [MutationTrigger<D>, UseMutationStateResult<D, R>];
845
+ type TypedUseMutation<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseMutation<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
846
+ type MutationTrigger<D extends MutationDefinition<any, any, any, any>> = {
847
+ /**
848
+ * Triggers the mutation and returns a Promise.
849
+ * @remarks
850
+ * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
851
+ *
852
+ * @example
853
+ * ```ts
854
+ * // codeblock-meta title="Using .unwrap with async await"
855
+ * try {
856
+ * const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
857
+ * console.log('fulfilled', payload);
858
+ * } catch (error) {
859
+ * console.error('rejected', error);
860
+ * }
861
+ * ```
862
+ */
863
+ (arg: QueryArgFrom<D>): MutationActionCreatorResult<D>;
864
+ };
865
+ type TypedMutationTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = MutationTrigger<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
866
+
867
+ type QueryHookNames<Definitions extends EndpointDefinitions> = {
868
+ [K in keyof Definitions as Definitions[K] extends {
869
+ type: DefinitionType.query;
870
+ } ? `use${Capitalize<K & string>}Query` : never]: UseQuery<Extract<Definitions[K], QueryDefinition<any, any, any, any>>>;
871
+ };
872
+ type LazyQueryHookNames<Definitions extends EndpointDefinitions> = {
873
+ [K in keyof Definitions as Definitions[K] extends {
874
+ type: DefinitionType.query;
875
+ } ? `useLazy${Capitalize<K & string>}Query` : never]: UseLazyQuery<Extract<Definitions[K], QueryDefinition<any, any, any, any>>>;
876
+ };
877
+ type InfiniteQueryHookNames<Definitions extends EndpointDefinitions> = {
878
+ [K in keyof Definitions as Definitions[K] extends {
879
+ type: DefinitionType.infinitequery;
880
+ } ? `use${Capitalize<K & string>}InfiniteQuery` : never]: UseInfiniteQuery<Extract<Definitions[K], InfiniteQueryDefinition<any, any, any, any, any>>>;
881
+ };
882
+ type MutationHookNames<Definitions extends EndpointDefinitions> = {
883
+ [K in keyof Definitions as Definitions[K] extends {
884
+ type: DefinitionType.mutation;
885
+ } ? `use${Capitalize<K & string>}Mutation` : never]: UseMutation<Extract<Definitions[K], MutationDefinition<any, any, any, any>>>;
886
+ };
887
+ type HooksWithUniqueNames<Definitions extends EndpointDefinitions> = QueryHookNames<Definitions> & LazyQueryHookNames<Definitions> & InfiniteQueryHookNames<Definitions> & MutationHookNames<Definitions>;
888
+
889
+ export declare const reactHooksModuleName: unique symbol;
890
+ type ReactHooksModule = typeof reactHooksModuleName;
891
+ declare module '@reduxjs/toolkit/query' {
892
+ interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
893
+ [reactHooksModuleName]: {
894
+ /**
895
+ * Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.
896
+ */
897
+ endpoints: {
898
+ [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? QueryHooks<Definitions[K]> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? MutationHooks<Definitions[K]> : Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryHooks<Definitions[K]> : never;
899
+ };
900
+ /**
901
+ * A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.
902
+ */
903
+ usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, options?: PrefetchOptions): (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => void;
904
+ } & HooksWithUniqueNames<Definitions>;
905
+ }
906
+ }
907
+ type RR = typeof react_redux;
908
+ interface ReactHooksModuleOptions {
909
+ /**
910
+ * The hooks from React Redux to be used
911
+ */
912
+ hooks?: {
913
+ /**
914
+ * The version of the `useDispatch` hook to be used
915
+ */
916
+ useDispatch: RR['useDispatch'];
917
+ /**
918
+ * The version of the `useSelector` hook to be used
919
+ */
920
+ useSelector: RR['useSelector'];
921
+ /**
922
+ * The version of the `useStore` hook to be used
923
+ */
924
+ useStore: RR['useStore'];
925
+ };
926
+ /**
927
+ * The version of the `batchedUpdates` function to be used
928
+ */
929
+ batch?: RR['batch'];
930
+ /**
931
+ * Enables performing asynchronous tasks immediately within a render.
932
+ *
933
+ * @example
934
+ *
935
+ * ```ts
936
+ * import {
937
+ * buildCreateApi,
938
+ * coreModule,
939
+ * reactHooksModule
940
+ * } from '@reduxjs/toolkit/query/react'
941
+ *
942
+ * const createApi = buildCreateApi(
943
+ * coreModule(),
944
+ * reactHooksModule({ unstable__sideEffectsInRender: true })
945
+ * )
946
+ * ```
947
+ */
948
+ unstable__sideEffectsInRender?: boolean;
949
+ /**
950
+ * A selector creator (usually from `reselect`, or matching the same signature)
951
+ */
952
+ createSelector?: CreateSelectorFunction<any, any, any>;
953
+ }
954
+ /**
955
+ * Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.
956
+ *
957
+ * @example
958
+ * ```ts
959
+ * const MyContext = React.createContext<ReactReduxContextValue | null>(null);
960
+ * const customCreateApi = buildCreateApi(
961
+ * coreModule(),
962
+ * reactHooksModule({
963
+ * hooks: {
964
+ * useDispatch: createDispatchHook(MyContext),
965
+ * useSelector: createSelectorHook(MyContext),
966
+ * useStore: createStoreHook(MyContext)
967
+ * }
968
+ * })
969
+ * );
970
+ * ```
971
+ *
972
+ * @returns A module for use with `buildCreateApi`
973
+ */
974
+ declare const reactHooksModule: ({ batch, hooks, createSelector, unstable__sideEffectsInRender, ...rest }?: ReactHooksModuleOptions) => Module<ReactHooksModule>;
975
+
976
+ /**
977
+ * Can be used as a `Provider` if you **do not already have a Redux store**.
978
+ *
979
+ * @example
980
+ * ```tsx
981
+ * // codeblock-meta no-transpile title="Basic usage - wrap your App with ApiProvider"
982
+ * import * as React from 'react';
983
+ * import { ApiProvider } from '@reduxjs/toolkit/query/react';
984
+ * import { Pokemon } from './features/Pokemon';
985
+ *
986
+ * function App() {
987
+ * return (
988
+ * <ApiProvider api={api}>
989
+ * <Pokemon />
990
+ * </ApiProvider>
991
+ * );
992
+ * }
993
+ * ```
994
+ *
995
+ * @remarks
996
+ * Using this together with an existing redux store, both will
997
+ * conflict with each other - please use the traditional redux setup
998
+ * in that case.
999
+ */
1000
+ declare function ApiProvider(props: {
1001
+ children: any;
1002
+ api: Api<any, {}, any, any>;
1003
+ setupListeners?: Parameters<typeof setupListeners>[1] | false;
1004
+ context?: Context<ReactReduxContextValue | null>;
1005
+ }): React.JSX.Element;
1006
+
1007
+ declare const createApi: _reduxjs_toolkit_query.CreateApi<typeof _reduxjs_toolkit_query.coreModuleName | typeof reactHooksModuleName>;
1008
+
1009
+ export { ApiProvider, type TypedInfiniteQueryStateSelector, type TypedLazyInfiniteQueryTrigger, type TypedLazyQueryTrigger, type TypedMutationTrigger, type TypedQueryStateSelector, type TypedUseInfiniteQuery, type TypedUseInfiniteQueryHookResult, type TypedUseInfiniteQueryState, type TypedUseInfiniteQueryStateOptions, type TypedUseInfiniteQueryStateResult, type TypedUseInfiniteQuerySubscription, type TypedUseInfiniteQuerySubscriptionResult, type TypedUseLazyQuery, type TypedUseLazyQueryStateResult, type TypedUseLazyQuerySubscription, type TypedUseMutation, type TypedUseMutationResult, type TypedUseMutationStateOptions, type TypedUseQuery, type TypedUseQueryHookResult, type TypedUseQueryState, type TypedUseQueryStateOptions, type TypedUseQueryStateResult, type TypedUseQuerySubscription, type TypedUseQuerySubscriptionOptions, type TypedUseQuerySubscriptionResult, createApi, reactHooksModule };