@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,727 @@
1
+ /**
2
+ * Note: this file should import all other files for type discovery and declaration merging
3
+ */
4
+ import type {
5
+ ActionCreatorWithPayload,
6
+ Dispatch,
7
+ Middleware,
8
+ Reducer,
9
+ ThunkAction,
10
+ ThunkDispatch,
11
+ UnknownAction,
12
+ } from '@reduxjs/toolkit'
13
+ import { enablePatches } from '../utils/immerImports'
14
+ import type { Api, Module } from '../apiTypes'
15
+ import type { BaseQueryFn } from '../baseQueryTypes'
16
+ import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
17
+ import type {
18
+ AssertTagTypes,
19
+ EndpointDefinitions,
20
+ InfiniteQueryDefinition,
21
+ MutationDefinition,
22
+ QueryArgFrom,
23
+ QueryArgFromAnyQuery,
24
+ QueryDefinition,
25
+ TagDescription,
26
+ } from '../endpointDefinitions'
27
+ import {
28
+ isInfiniteQueryDefinition,
29
+ isMutationDefinition,
30
+ isQueryDefinition,
31
+ } from '../endpointDefinitions'
32
+ import { assertCast, safeAssign } from '../tsHelpers'
33
+ import type {
34
+ CombinedState,
35
+ MutationKeys,
36
+ QueryKeys,
37
+ RootState,
38
+ } from './apiState'
39
+ import type {
40
+ BuildInitiateApiEndpointMutation,
41
+ BuildInitiateApiEndpointQuery,
42
+ MutationActionCreatorResult,
43
+ QueryActionCreatorResult,
44
+ InfiniteQueryActionCreatorResult,
45
+ BuildInitiateApiEndpointInfiniteQuery,
46
+ } from './buildInitiate'
47
+ import { buildInitiate } from './buildInitiate'
48
+ import type {
49
+ ReferenceCacheCollection,
50
+ ReferenceCacheLifecycle,
51
+ ReferenceQueryLifecycle,
52
+ } from './buildMiddleware'
53
+ import { buildMiddleware } from './buildMiddleware'
54
+ import type {
55
+ BuildSelectorsApiEndpointInfiniteQuery,
56
+ BuildSelectorsApiEndpointMutation,
57
+ BuildSelectorsApiEndpointQuery,
58
+ } from './buildSelectors'
59
+ import { buildSelectors } from './buildSelectors'
60
+ import type { SliceActions, UpsertEntries } from './buildSlice'
61
+ import { buildSlice } from './buildSlice'
62
+ import type {
63
+ AllQueryKeys,
64
+ BuildThunksApiEndpointInfiniteQuery,
65
+ BuildThunksApiEndpointMutation,
66
+ BuildThunksApiEndpointQuery,
67
+ PatchQueryDataThunk,
68
+ QueryArgFromAnyQueryDefinition,
69
+ UpdateQueryDataThunk,
70
+ UpsertQueryDataThunk,
71
+ } from './buildThunks'
72
+ import { buildThunks } from './buildThunks'
73
+ import { createSelector as _createSelector } from './rtkImports'
74
+ import { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners'
75
+ import type { InternalMiddlewareState } from './buildMiddleware/types'
76
+ import { getOrInsertComputed } from '../utils'
77
+ import type { CreateSelectorFunction } from 'reselect'
78
+
79
+ /**
80
+ * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_
81
+ * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value
82
+ *
83
+ * @overloadSummary
84
+ * `force`
85
+ * - 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.
86
+ */
87
+ export type PrefetchOptions =
88
+ | {
89
+ ifOlderThan?: false | number
90
+ }
91
+ | { force?: boolean }
92
+
93
+ export const coreModuleName = /* @__PURE__ */ Symbol()
94
+ export type CoreModule =
95
+ | typeof coreModuleName
96
+ | ReferenceCacheLifecycle
97
+ | ReferenceQueryLifecycle
98
+ | ReferenceCacheCollection
99
+
100
+ export type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>
101
+
102
+ export interface ApiModules<
103
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
104
+ BaseQuery extends BaseQueryFn,
105
+ Definitions extends EndpointDefinitions,
106
+ ReducerPath extends string,
107
+ TagTypes extends string,
108
+ > {
109
+ [coreModuleName]: {
110
+ /**
111
+ * This api's reducer should be mounted at `store[api.reducerPath]`.
112
+ *
113
+ * @example
114
+ * ```ts
115
+ * configureStore({
116
+ * reducer: {
117
+ * [api.reducerPath]: api.reducer,
118
+ * },
119
+ * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
120
+ * })
121
+ * ```
122
+ */
123
+ reducerPath: ReducerPath
124
+ /**
125
+ * Internal actions not part of the public API. Note: These are subject to change at any given time.
126
+ */
127
+ internalActions: InternalActions
128
+ /**
129
+ * A standard redux reducer that enables core functionality. Make sure it's included in your store.
130
+ *
131
+ * @example
132
+ * ```ts
133
+ * configureStore({
134
+ * reducer: {
135
+ * [api.reducerPath]: api.reducer,
136
+ * },
137
+ * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
138
+ * })
139
+ * ```
140
+ */
141
+ reducer: Reducer<
142
+ CombinedState<Definitions, TagTypes, ReducerPath>,
143
+ UnknownAction
144
+ >
145
+ /**
146
+ * 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.
147
+ *
148
+ * @example
149
+ * ```ts
150
+ * configureStore({
151
+ * reducer: {
152
+ * [api.reducerPath]: api.reducer,
153
+ * },
154
+ * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
155
+ * })
156
+ * ```
157
+ */
158
+ middleware: Middleware<
159
+ {},
160
+ RootState<Definitions, string, ReducerPath>,
161
+ ThunkDispatch<any, any, UnknownAction>
162
+ >
163
+ /**
164
+ * A collection of utility thunks for various situations.
165
+ */
166
+ util: {
167
+ /**
168
+ * A thunk that (if dispatched) will return a specific running query, identified
169
+ * by `endpointName` and `arg`.
170
+ * If that query is not running, dispatching the thunk will result in `undefined`.
171
+ *
172
+ * Can be used to await a specific query triggered in any way,
173
+ * including via hook calls or manually dispatching `initiate` actions.
174
+ *
175
+ * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
176
+ */
177
+ getRunningQueryThunk<EndpointName extends AllQueryKeys<Definitions>>(
178
+ endpointName: EndpointName,
179
+ arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>,
180
+ ): ThunkWithReturnValue<
181
+ | QueryActionCreatorResult<
182
+ Definitions[EndpointName] & { type: 'query' }
183
+ >
184
+ | InfiniteQueryActionCreatorResult<
185
+ Definitions[EndpointName] & { type: 'infinitequery' }
186
+ >
187
+ | undefined
188
+ >
189
+
190
+ /**
191
+ * A thunk that (if dispatched) will return a specific running mutation, identified
192
+ * by `endpointName` and `fixedCacheKey` or `requestId`.
193
+ * If that mutation is not running, dispatching the thunk will result in `undefined`.
194
+ *
195
+ * Can be used to await a specific mutation triggered in any way,
196
+ * including via hook trigger functions or manually dispatching `initiate` actions.
197
+ *
198
+ * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
199
+ */
200
+ getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(
201
+ endpointName: EndpointName,
202
+ fixedCacheKeyOrRequestId: string,
203
+ ): ThunkWithReturnValue<
204
+ | MutationActionCreatorResult<
205
+ Definitions[EndpointName] & { type: 'mutation' }
206
+ >
207
+ | undefined
208
+ >
209
+
210
+ /**
211
+ * A thunk that (if dispatched) will return all running queries.
212
+ *
213
+ * Useful for SSR scenarios to await all running queries triggered in any way,
214
+ * including via hook calls or manually dispatching `initiate` actions.
215
+ *
216
+ * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
217
+ */
218
+ getRunningQueriesThunk(): ThunkWithReturnValue<
219
+ Array<
220
+ QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>
221
+ >
222
+ >
223
+
224
+ /**
225
+ * A thunk that (if dispatched) will return all running mutations.
226
+ *
227
+ * Useful for SSR scenarios to await all running mutations triggered in any way,
228
+ * including via hook calls or manually dispatching `initiate` actions.
229
+ *
230
+ * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
231
+ */
232
+ getRunningMutationsThunk(): ThunkWithReturnValue<
233
+ Array<MutationActionCreatorResult<any>>
234
+ >
235
+
236
+ /**
237
+ * A Redux thunk that can be used to manually trigger pre-fetching of data.
238
+ *
239
+ * 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.
240
+ *
241
+ * 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.
242
+ *
243
+ * @example
244
+ *
245
+ * ```ts no-transpile
246
+ * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))
247
+ * ```
248
+ */
249
+ prefetch<EndpointName extends QueryKeys<Definitions>>(
250
+ endpointName: EndpointName,
251
+ arg: QueryArgFrom<Definitions[EndpointName]>,
252
+ options?: PrefetchOptions,
253
+ ): ThunkAction<void, any, any, UnknownAction>
254
+ /**
255
+ * 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.
256
+ *
257
+ * 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.
258
+ *
259
+ * 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).
260
+ *
261
+ * 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.
262
+ *
263
+ * 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.
264
+ *
265
+ * @example
266
+ *
267
+ * ```ts
268
+ * const patchCollection = dispatch(
269
+ * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
270
+ * draftPosts.push({ id: 1, name: 'Teddy' })
271
+ * })
272
+ * )
273
+ * ```
274
+ */
275
+ updateQueryData: UpdateQueryDataThunk<
276
+ Definitions,
277
+ RootState<Definitions, string, ReducerPath>
278
+ >
279
+
280
+ /**
281
+ * A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.
282
+ *
283
+ * 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.
284
+ *
285
+ * 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.
286
+ *
287
+ * The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.
288
+ *
289
+ * 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.
290
+ *
291
+ * @example
292
+ *
293
+ * ```ts
294
+ * await dispatch(
295
+ * api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: "Hello!"})
296
+ * )
297
+ * ```
298
+ */
299
+ upsertQueryData: UpsertQueryDataThunk<
300
+ Definitions,
301
+ RootState<Definitions, string, ReducerPath>
302
+ >
303
+ /**
304
+ * 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.
305
+ *
306
+ * 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`.
307
+ *
308
+ * 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.
309
+ *
310
+ * 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.
311
+ *
312
+ * @example
313
+ * ```ts
314
+ * const patchCollection = dispatch(
315
+ * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
316
+ * draftPosts.push({ id: 1, name: 'Teddy' })
317
+ * })
318
+ * )
319
+ *
320
+ * // later
321
+ * dispatch(
322
+ * api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)
323
+ * )
324
+ *
325
+ * // or
326
+ * patchCollection.undo()
327
+ * ```
328
+ */
329
+ patchQueryData: PatchQueryDataThunk<
330
+ Definitions,
331
+ RootState<Definitions, string, ReducerPath>
332
+ >
333
+
334
+ /**
335
+ * 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'.
336
+ *
337
+ * @example
338
+ *
339
+ * ```ts
340
+ * dispatch(api.util.resetApiState())
341
+ * ```
342
+ */
343
+ resetApiState: SliceActions['resetApiState']
344
+
345
+ upsertQueryEntries: UpsertEntries<Definitions>
346
+
347
+ /**
348
+ * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).
349
+ *
350
+ * 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.
351
+ *
352
+ * 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.
353
+ *
354
+ * 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:
355
+ *
356
+ * - `[TagType]`
357
+ * - `[{ type: TagType }]`
358
+ * - `[{ type: TagType, id: number | string }]`
359
+ *
360
+ * @example
361
+ *
362
+ * ```ts
363
+ * dispatch(api.util.invalidateTags(['Post']))
364
+ * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))
365
+ * dispatch(
366
+ * api.util.invalidateTags([
367
+ * { type: 'Post', id: 1 },
368
+ * { type: 'Post', id: 'LIST' },
369
+ * ])
370
+ * )
371
+ * ```
372
+ */
373
+ invalidateTags: ActionCreatorWithPayload<
374
+ Array<TagDescription<TagTypes> | null | undefined>,
375
+ string
376
+ >
377
+
378
+ /**
379
+ * A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.
380
+ *
381
+ * 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.
382
+ */
383
+ selectInvalidatedBy: (
384
+ state: RootState<Definitions, string, ReducerPath>,
385
+ tags: ReadonlyArray<TagDescription<TagTypes> | null | undefined>,
386
+ ) => Array<{
387
+ endpointName: string
388
+ originalArgs: any
389
+ queryCacheKey: string
390
+ }>
391
+
392
+ /**
393
+ * A function to select all arguments currently cached for a given endpoint.
394
+ *
395
+ * 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.
396
+ */
397
+ selectCachedArgsForQuery: <QueryName extends AllQueryKeys<Definitions>>(
398
+ state: RootState<Definitions, string, ReducerPath>,
399
+ queryName: QueryName,
400
+ ) => Array<QueryArgFromAnyQuery<Definitions[QueryName]>>
401
+ }
402
+ /**
403
+ * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.
404
+ */
405
+ endpoints: {
406
+ [K in keyof Definitions]: Definitions[K] extends QueryDefinition<
407
+ any,
408
+ any,
409
+ any,
410
+ any,
411
+ any
412
+ >
413
+ ? ApiEndpointQuery<Definitions[K], Definitions>
414
+ : Definitions[K] extends MutationDefinition<any, any, any, any, any>
415
+ ? ApiEndpointMutation<Definitions[K], Definitions>
416
+ : Definitions[K] extends InfiniteQueryDefinition<
417
+ any,
418
+ any,
419
+ any,
420
+ any,
421
+ any
422
+ >
423
+ ? ApiEndpointInfiniteQuery<Definitions[K], Definitions>
424
+ : never
425
+ }
426
+ }
427
+ }
428
+
429
+ export interface ApiEndpointQuery<
430
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
431
+ Definition extends QueryDefinition<any, any, any, any, any>,
432
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
433
+ Definitions extends EndpointDefinitions,
434
+ > extends BuildThunksApiEndpointQuery<Definition>,
435
+ BuildInitiateApiEndpointQuery<Definition>,
436
+ BuildSelectorsApiEndpointQuery<Definition, Definitions> {
437
+ name: string
438
+ /**
439
+ * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
440
+ */
441
+ Types: NonNullable<Definition['Types']>
442
+ }
443
+
444
+ export interface ApiEndpointInfiniteQuery<
445
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
446
+ Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
447
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
448
+ Definitions extends EndpointDefinitions,
449
+ > extends BuildThunksApiEndpointInfiniteQuery<Definition>,
450
+ BuildInitiateApiEndpointInfiniteQuery<Definition>,
451
+ BuildSelectorsApiEndpointInfiniteQuery<Definition, Definitions> {
452
+ name: string
453
+ /**
454
+ * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
455
+ */
456
+ Types: NonNullable<Definition['Types']>
457
+ }
458
+
459
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
460
+ export interface ApiEndpointMutation<
461
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
462
+ Definition extends MutationDefinition<any, any, any, any, any>,
463
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
464
+ Definitions extends EndpointDefinitions,
465
+ > extends BuildThunksApiEndpointMutation<Definition>,
466
+ BuildInitiateApiEndpointMutation<Definition>,
467
+ BuildSelectorsApiEndpointMutation<Definition, Definitions> {
468
+ name: string
469
+ /**
470
+ * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
471
+ */
472
+ Types: NonNullable<Definition['Types']>
473
+ }
474
+
475
+ export type ListenerActions = {
476
+ /**
477
+ * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior
478
+ * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners
479
+ */
480
+ onOnline: typeof onOnline
481
+ onOffline: typeof onOffline
482
+ /**
483
+ * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior
484
+ * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners
485
+ */
486
+ onFocus: typeof onFocus
487
+ onFocusLost: typeof onFocusLost
488
+ }
489
+
490
+ export type InternalActions = SliceActions & ListenerActions
491
+
492
+ export interface CoreModuleOptions {
493
+ /**
494
+ * A selector creator (usually from `reselect`, or matching the same signature)
495
+ */
496
+ createSelector?: CreateSelectorFunction<any, any, any>
497
+ }
498
+
499
+ /**
500
+ * Creates a module containing the basic redux logic for use with `buildCreateApi`.
501
+ *
502
+ * @example
503
+ * ```ts
504
+ * const createBaseApi = buildCreateApi(coreModule());
505
+ * ```
506
+ */
507
+ export const coreModule = ({
508
+ createSelector = _createSelector,
509
+ }: CoreModuleOptions = {}): Module<CoreModule> => ({
510
+ name: coreModuleName,
511
+ init(
512
+ api,
513
+ {
514
+ baseQuery,
515
+ tagTypes,
516
+ reducerPath,
517
+ serializeQueryArgs,
518
+ keepUnusedDataFor,
519
+ refetchOnMountOrArgChange,
520
+ refetchOnFocus,
521
+ refetchOnReconnect,
522
+ invalidationBehavior,
523
+ onSchemaFailure,
524
+ catchSchemaFailure,
525
+ skipSchemaValidation,
526
+ },
527
+ context,
528
+ ) {
529
+ enablePatches()
530
+
531
+ assertCast<InternalSerializeQueryArgs>(serializeQueryArgs)
532
+
533
+ const assertTagType: AssertTagTypes = (tag) => {
534
+ if (
535
+ typeof process !== 'undefined' &&
536
+ process.env.NODE_ENV === 'development'
537
+ ) {
538
+ if (!tagTypes.includes(tag.type as any)) {
539
+ console.error(
540
+ `Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`,
541
+ )
542
+ }
543
+ }
544
+ return tag
545
+ }
546
+
547
+ Object.assign(api, {
548
+ reducerPath,
549
+ endpoints: {},
550
+ internalActions: {
551
+ onOnline,
552
+ onOffline,
553
+ onFocus,
554
+ onFocusLost,
555
+ },
556
+ util: {},
557
+ })
558
+
559
+ const selectors = buildSelectors({
560
+ serializeQueryArgs: serializeQueryArgs as any,
561
+ reducerPath,
562
+ createSelector,
563
+ })
564
+
565
+ const {
566
+ selectInvalidatedBy,
567
+ selectCachedArgsForQuery,
568
+ buildQuerySelector,
569
+ buildInfiniteQuerySelector,
570
+ buildMutationSelector,
571
+ } = selectors
572
+
573
+ safeAssign(api.util, { selectInvalidatedBy, selectCachedArgsForQuery })
574
+
575
+ const {
576
+ queryThunk,
577
+ infiniteQueryThunk,
578
+ mutationThunk,
579
+ patchQueryData,
580
+ updateQueryData,
581
+ upsertQueryData,
582
+ prefetch,
583
+ buildMatchThunkActions,
584
+ } = buildThunks({
585
+ baseQuery,
586
+ reducerPath,
587
+ context,
588
+ api,
589
+ serializeQueryArgs,
590
+ assertTagType,
591
+ selectors,
592
+ onSchemaFailure,
593
+ catchSchemaFailure,
594
+ skipSchemaValidation,
595
+ })
596
+
597
+ const { reducer, actions: sliceActions } = buildSlice({
598
+ context,
599
+ queryThunk,
600
+ infiniteQueryThunk,
601
+ mutationThunk,
602
+ serializeQueryArgs,
603
+ reducerPath,
604
+ assertTagType,
605
+ config: {
606
+ refetchOnFocus,
607
+ refetchOnReconnect,
608
+ refetchOnMountOrArgChange,
609
+ keepUnusedDataFor,
610
+ reducerPath,
611
+ invalidationBehavior,
612
+ },
613
+ })
614
+
615
+ safeAssign(api.util, {
616
+ patchQueryData,
617
+ updateQueryData,
618
+ upsertQueryData,
619
+ prefetch,
620
+ resetApiState: sliceActions.resetApiState,
621
+ upsertQueryEntries: sliceActions.cacheEntriesUpserted as any,
622
+ })
623
+ safeAssign(api.internalActions, sliceActions)
624
+
625
+ const internalStateMap = new WeakMap<Dispatch, InternalMiddlewareState>()
626
+
627
+ const getInternalState = (dispatch: Dispatch) => {
628
+ const state = getOrInsertComputed(internalStateMap, dispatch, () => ({
629
+ currentSubscriptions: new Map(),
630
+ currentPolls: new Map(),
631
+ runningQueries: new Map(),
632
+ runningMutations: new Map(),
633
+ }))
634
+
635
+ return state
636
+ }
637
+
638
+ const {
639
+ buildInitiateQuery,
640
+ buildInitiateInfiniteQuery,
641
+ buildInitiateMutation,
642
+ getRunningMutationThunk,
643
+ getRunningMutationsThunk,
644
+ getRunningQueriesThunk,
645
+ getRunningQueryThunk,
646
+ } = buildInitiate({
647
+ queryThunk,
648
+ mutationThunk,
649
+ infiniteQueryThunk,
650
+ api,
651
+ serializeQueryArgs: serializeQueryArgs as any,
652
+ context,
653
+ getInternalState,
654
+ })
655
+
656
+ safeAssign(api.util, {
657
+ getRunningMutationThunk,
658
+ getRunningMutationsThunk,
659
+ getRunningQueryThunk,
660
+ getRunningQueriesThunk,
661
+ })
662
+
663
+ const { middleware, actions: middlewareActions } = buildMiddleware({
664
+ reducerPath,
665
+ context,
666
+ queryThunk,
667
+ mutationThunk,
668
+ infiniteQueryThunk,
669
+ api,
670
+ assertTagType,
671
+ selectors,
672
+ getRunningQueryThunk,
673
+ getInternalState,
674
+ })
675
+ safeAssign(api.util, middlewareActions)
676
+
677
+ safeAssign(api, { reducer: reducer as any, middleware })
678
+
679
+ return {
680
+ name: coreModuleName,
681
+ injectEndpoint(endpointName, definition) {
682
+ const anyApi = api as any as Api<
683
+ any,
684
+ Record<string, any>,
685
+ string,
686
+ string,
687
+ CoreModule
688
+ >
689
+ const endpoint = (anyApi.endpoints[endpointName] ??= {} as any)
690
+
691
+ if (isQueryDefinition(definition)) {
692
+ safeAssign(
693
+ endpoint,
694
+ {
695
+ name: endpointName,
696
+ select: buildQuerySelector(endpointName, definition),
697
+ initiate: buildInitiateQuery(endpointName, definition),
698
+ },
699
+ buildMatchThunkActions(queryThunk, endpointName),
700
+ )
701
+ }
702
+ if (isMutationDefinition(definition)) {
703
+ safeAssign(
704
+ endpoint,
705
+ {
706
+ name: endpointName,
707
+ select: buildMutationSelector(),
708
+ initiate: buildInitiateMutation(endpointName),
709
+ },
710
+ buildMatchThunkActions(mutationThunk, endpointName),
711
+ )
712
+ }
713
+ if (isInfiniteQueryDefinition(definition)) {
714
+ safeAssign(
715
+ endpoint,
716
+ {
717
+ name: endpointName,
718
+ select: buildInfiniteQuerySelector(endpointName, definition),
719
+ initiate: buildInitiateInfiniteQuery(endpointName, definition),
720
+ },
721
+ buildMatchThunkActions(queryThunk, endpointName),
722
+ )
723
+ }
724
+ },
725
+ }
726
+ },
727
+ })