@octanejs/redux-toolkit 0.1.0

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.
@@ -0,0 +1,2024 @@
1
+ import type { Selector, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';
2
+ import type {
3
+ Api,
4
+ ApiContext,
5
+ ApiEndpointMutation,
6
+ ApiEndpointQuery,
7
+ BaseQueryFn,
8
+ CoreModule,
9
+ EndpointDefinitions,
10
+ InfiniteData,
11
+ InfiniteQueryActionCreatorResult,
12
+ InfiniteQueryArgFrom,
13
+ InfiniteQueryDefinition,
14
+ InfiniteQueryResultSelectorResult,
15
+ InfiniteQuerySubState,
16
+ MutationActionCreatorResult,
17
+ MutationDefinition,
18
+ MutationResultSelectorResult,
19
+ PageParamFrom,
20
+ PrefetchOptions,
21
+ QueryActionCreatorResult,
22
+ QueryArgFrom,
23
+ QueryCacheKey,
24
+ QueryDefinition,
25
+ QueryKeys,
26
+ QueryResultSelectorResult,
27
+ QuerySubState,
28
+ ResultTypeFrom,
29
+ RootState,
30
+ SerializeQueryArgs,
31
+ SkipToken,
32
+ SubscriptionOptions,
33
+ TSHelpersId,
34
+ TSHelpersOverride,
35
+ } from '@reduxjs/toolkit/query';
36
+ import type { UninitializedValue } from './constants';
37
+ import { UNINITIALIZED_VALUE } from './constants';
38
+ import type { ReactHooksModuleOptions } from './module';
39
+ import {
40
+ useCallback,
41
+ useDebugValue,
42
+ useEffect,
43
+ useLayoutEffect,
44
+ useMemo,
45
+ useRef,
46
+ useState,
47
+ } from 'octane';
48
+ import { shallowEqual } from '@octanejs/redux';
49
+ import { QueryStatus, skipToken } from '@reduxjs/toolkit/query';
50
+ import type { Store } from 'redux';
51
+ import { useStableQueryArgs } from './useSerializedStableValue';
52
+ import { useShallowStableValue } from './useShallowStableValue';
53
+
54
+ type DependencyList = any[];
55
+ type InfiniteQueryDirection = 'forward' | 'backward';
56
+ type RefObject<T> = { current: T };
57
+ type SubscriptionSelectors = {
58
+ isRequestSubscribed(queryCacheKey: string, requestId: string): boolean;
59
+ };
60
+ type StartInfiniteQueryActionCreator<_D> = (arg: any, options?: any) => any;
61
+
62
+ const isInfiniteQueryDefinition = (definition: { type?: string }) =>
63
+ definition.type === 'infinitequery';
64
+
65
+ // Copy-pasted from React-Redux
66
+ const canUseDOM = () =>
67
+ !!(
68
+ typeof window !== 'undefined' &&
69
+ typeof window.document !== 'undefined' &&
70
+ typeof window.document.createElement !== 'undefined'
71
+ );
72
+
73
+ const isDOM = /* @__PURE__ */ canUseDOM();
74
+
75
+ // Under React Native, we know that we always want to use useLayoutEffect
76
+
77
+ const isRunningInReactNative = () =>
78
+ typeof navigator !== 'undefined' && navigator.product === 'ReactNative';
79
+
80
+ const isReactNative = /* @__PURE__ */ isRunningInReactNative();
81
+
82
+ const getUseIsomorphicLayoutEffect = () => (isDOM || isReactNative ? useLayoutEffect : useEffect);
83
+
84
+ export const useIsomorphicLayoutEffect = /* @__PURE__ */ getUseIsomorphicLayoutEffect();
85
+
86
+ export type QueryHooks<Definition extends QueryDefinition<any, any, any, any, any>> = {
87
+ useQuery: UseQuery<Definition>;
88
+ useLazyQuery: UseLazyQuery<Definition>;
89
+ useQuerySubscription: UseQuerySubscription<Definition>;
90
+ useLazyQuerySubscription: UseLazyQuerySubscription<Definition>;
91
+ useQueryState: UseQueryState<Definition>;
92
+ };
93
+
94
+ export type InfiniteQueryHooks<
95
+ Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
96
+ > = {
97
+ useInfiniteQuery: UseInfiniteQuery<Definition>;
98
+ useInfiniteQuerySubscription: UseInfiniteQuerySubscription<Definition>;
99
+ useInfiniteQueryState: UseInfiniteQueryState<Definition>;
100
+ };
101
+
102
+ export type MutationHooks<Definition extends MutationDefinition<any, any, any, any, any>> = {
103
+ useMutation: UseMutation<Definition>;
104
+ };
105
+
106
+ /**
107
+ * 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.
108
+ *
109
+ * 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.
110
+ *
111
+ * This hook combines the functionality of both [`useQueryState`](#usequerystate) and [`useQuerySubscription`](#usequerysubscription) together, and is intended to be used in the majority of situations.
112
+ *
113
+ * #### Features
114
+ *
115
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
116
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
117
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
118
+ * - Returns the latest request status and cached data from the Redux store
119
+ * - Re-renders as the request status changes and data becomes available
120
+ */
121
+ export type UseQuery<D extends QueryDefinition<any, any, any, any>> = <
122
+ R extends Record<string, any> = UseQueryStateDefaultResult<D>,
123
+ >(
124
+ arg: QueryArgFrom<D> | SkipToken,
125
+ options?: UseQuerySubscriptionOptions & UseQueryStateOptions<D, R>,
126
+ ) => UseQueryHookResult<D, R>;
127
+
128
+ export type TypedUseQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuery<
129
+ QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
130
+ >;
131
+
132
+ export type UseQueryHookResult<
133
+ D extends QueryDefinition<any, any, any, any>,
134
+ R = UseQueryStateDefaultResult<D>,
135
+ > = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>;
136
+
137
+ /**
138
+ * Helper type to manually type the result
139
+ * of the `useQuery` hook in userland code.
140
+ */
141
+ export type TypedUseQueryHookResult<
142
+ ResultType,
143
+ QueryArg,
144
+ BaseQuery extends BaseQueryFn,
145
+ R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>,
146
+ > = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> &
147
+ TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>;
148
+
149
+ export type UseQuerySubscriptionOptions = SubscriptionOptions & {
150
+ /**
151
+ * Prevents a query from automatically running.
152
+ *
153
+ * @remarks
154
+ * When `skip` is true (or `skipToken` is passed in as `arg`):
155
+ *
156
+ * - **If the query has cached data:**
157
+ * * 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
158
+ * * The query will have a status of `uninitialized`
159
+ * * If `skip: false` is set after the initial load, the cached result will be used
160
+ * - **If the query does not have cached data:**
161
+ * * The query will have a status of `uninitialized`
162
+ * * The query will not exist in the state when viewed with the dev tools
163
+ * * The query will not automatically fetch on mount
164
+ * * The query will not automatically run when additional components with the same query are added that do run
165
+ *
166
+ * @example
167
+ * ```tsx
168
+ * // codeblock-meta no-transpile title="Skip example"
169
+ * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
170
+ * const { data, error, status } = useGetPokemonByNameQuery(name, {
171
+ * skip,
172
+ * });
173
+ *
174
+ * return (
175
+ * <div>
176
+ * {name} - {status}
177
+ * </div>
178
+ * );
179
+ * };
180
+ * ```
181
+ */
182
+ skip?: boolean;
183
+ /**
184
+ * 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.
185
+ * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
186
+ * - `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.
187
+ * - `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.
188
+ *
189
+ * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
190
+ */
191
+ refetchOnMountOrArgChange?: boolean | number;
192
+ };
193
+
194
+ /**
195
+ * Provides a way to reference the options accepted by the `useQuerySubscription`
196
+ * hook in userland code.
197
+ *
198
+ * Unlike other `Typed*` wrappers, this type has no generic parameters since
199
+ * {@linkcode UseQuerySubscriptionOptions} does not depend on a specific query
200
+ * definition.
201
+ *
202
+ * @since 2.11.3
203
+ * @public
204
+ */
205
+ export type TypedUseQuerySubscriptionOptions = UseQuerySubscriptionOptions;
206
+
207
+ /**
208
+ * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.
209
+ *
210
+ * 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.
211
+ *
212
+ * Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).
213
+ *
214
+ * #### Features
215
+ *
216
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
217
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
218
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
219
+ */
220
+ export type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (
221
+ arg: QueryArgFrom<D> | SkipToken,
222
+ options?: UseQuerySubscriptionOptions,
223
+ ) => UseQuerySubscriptionResult<D>;
224
+
225
+ export type TypedUseQuerySubscription<
226
+ ResultType,
227
+ QueryArg,
228
+ BaseQuery extends BaseQueryFn,
229
+ > = UseQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
230
+
231
+ export type UseQuerySubscriptionResult<D extends QueryDefinition<any, any, any, any>> = Pick<
232
+ QueryActionCreatorResult<D>,
233
+ 'refetch'
234
+ >;
235
+
236
+ /**
237
+ * Helper type to manually type the result
238
+ * of the `useQuerySubscription` hook in userland code.
239
+ */
240
+ export type TypedUseQuerySubscriptionResult<
241
+ ResultType,
242
+ QueryArg,
243
+ BaseQuery extends BaseQueryFn,
244
+ > = UseQuerySubscriptionResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
245
+
246
+ export type UseLazyQueryLastPromiseInfo<D extends QueryDefinition<any, any, any, any>> = {
247
+ lastArg: QueryArgFrom<D>;
248
+ };
249
+
250
+ /**
251
+ * A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.
252
+ *
253
+ * This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).
254
+ *
255
+ * #### Features
256
+ *
257
+ * - Manual control over firing a request to retrieve data
258
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
259
+ * - Returns the latest request status and cached data from the Redux store
260
+ * - Re-renders as the request status changes and data becomes available
261
+ * - 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
262
+ *
263
+ * #### Note
264
+ *
265
+ * 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.
266
+ */
267
+ export type UseLazyQuery<D extends QueryDefinition<any, any, any, any>> = <
268
+ R extends Record<string, any> = UseQueryStateDefaultResult<D>,
269
+ >(
270
+ options?: SubscriptionOptions & Omit<UseQueryStateOptions<D, R>, 'skip'>,
271
+ ) => [LazyQueryTrigger<D>, UseLazyQueryStateResult<D, R>, UseLazyQueryLastPromiseInfo<D>];
272
+
273
+ export type TypedUseLazyQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuery<
274
+ QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
275
+ >;
276
+
277
+ export type UseLazyQueryStateResult<
278
+ D extends QueryDefinition<any, any, any, any>,
279
+ R = UseQueryStateDefaultResult<D>,
280
+ > = UseQueryStateResult<D, R> & {
281
+ /**
282
+ * Resets the hook state to its initial `uninitialized` state.
283
+ * This will also remove the last result from the cache.
284
+ */
285
+ reset: () => void;
286
+ };
287
+
288
+ /**
289
+ * Helper type to manually type the result
290
+ * of the `useLazyQuery` hook in userland code.
291
+ */
292
+ export type TypedUseLazyQueryStateResult<
293
+ ResultType,
294
+ QueryArg,
295
+ BaseQuery extends BaseQueryFn,
296
+ R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>,
297
+ > = UseLazyQueryStateResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;
298
+
299
+ export type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {
300
+ /**
301
+ * Triggers a lazy query.
302
+ *
303
+ * By default, this will start a new request even if there is already a value in the cache.
304
+ * 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`.
305
+ *
306
+ * @remarks
307
+ * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
308
+ *
309
+ * @example
310
+ * ```ts
311
+ * // codeblock-meta title="Using .unwrap with async await"
312
+ * try {
313
+ * const payload = await getUserById(1).unwrap();
314
+ * console.log('fulfilled', payload);
315
+ * } catch (error) {
316
+ * console.error('rejected', error);
317
+ * }
318
+ * ```
319
+ */
320
+ (arg: QueryArgFrom<D>, preferCacheValue?: boolean): QueryActionCreatorResult<D>;
321
+ };
322
+
323
+ export type TypedLazyQueryTrigger<
324
+ ResultType,
325
+ QueryArg,
326
+ BaseQuery extends BaseQueryFn,
327
+ > = LazyQueryTrigger<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
328
+
329
+ /**
330
+ * A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.
331
+ *
332
+ * Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).
333
+ *
334
+ * #### Features
335
+ *
336
+ * - Manual control over firing a request to retrieve data
337
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
338
+ * - 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
339
+ */
340
+ export type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (
341
+ options?: SubscriptionOptions,
342
+ ) => readonly [LazyQueryTrigger<D>, QueryArgFrom<D> | UninitializedValue, { reset: () => void }];
343
+
344
+ export type TypedUseLazyQuerySubscription<
345
+ ResultType,
346
+ QueryArg,
347
+ BaseQuery extends BaseQueryFn,
348
+ > = UseLazyQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
349
+
350
+ /**
351
+ * @internal
352
+ */
353
+ export type QueryStateSelector<
354
+ R extends Record<string, any>,
355
+ D extends QueryDefinition<any, any, any, any>,
356
+ > = (state: UseQueryStateDefaultResult<D>) => R;
357
+
358
+ /**
359
+ * Provides a way to define a strongly-typed version of
360
+ * {@linkcode QueryStateSelector} for use with a specific query.
361
+ * This is useful for scenarios where you want to create a "pre-typed"
362
+ * {@linkcode UseQueryStateOptions.selectFromResult | selectFromResult}
363
+ * function.
364
+ *
365
+ * @example
366
+ * <caption>#### __Create a strongly-typed `selectFromResult` selector function__</caption>
367
+ *
368
+ * ```tsx
369
+ * import type { TypedQueryStateSelector } from '@reduxjs/toolkit/query/react';
370
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
371
+ *
372
+ * type Post = {
373
+ * id: number;
374
+ * title: string;
375
+ * };
376
+ *
377
+ * type PostsApiResponse = {
378
+ * posts: Post[];
379
+ * total: number;
380
+ * skip: number;
381
+ * limit: number;
382
+ * };
383
+ *
384
+ * type QueryArgument = number | undefined;
385
+ *
386
+ * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>;
387
+ *
388
+ * type SelectedResult = Pick<PostsApiResponse, 'posts'>;
389
+ *
390
+ * const postsApiSlice = createApi({
391
+ * baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),
392
+ * reducerPath: 'postsApi',
393
+ * tagTypes: ['Posts'],
394
+ * endpoints: (build) => ({
395
+ * getPosts: build.query<PostsApiResponse, QueryArgument>({
396
+ * query: (limit = 5) => `?limit=${limit}&select=title`,
397
+ * }),
398
+ * }),
399
+ * });
400
+ *
401
+ * const { useGetPostsQuery } = postsApiSlice;
402
+ *
403
+ * function PostById({ id }: { id: number }) {
404
+ * const { post } = useGetPostsQuery(undefined, {
405
+ * selectFromResult: (state) => ({
406
+ * post: state.data?.posts.find((post) => post.id === id),
407
+ * }),
408
+ * });
409
+ *
410
+ * return <li>{post?.title}</li>;
411
+ * }
412
+ *
413
+ * const EMPTY_ARRAY: Post[] = [];
414
+ *
415
+ * const typedSelectFromResult: TypedQueryStateSelector<
416
+ * PostsApiResponse,
417
+ * QueryArgument,
418
+ * BaseQueryFunction,
419
+ * SelectedResult
420
+ * > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY });
421
+ *
422
+ * function PostsList() {
423
+ * const { posts } = useGetPostsQuery(undefined, {
424
+ * selectFromResult: typedSelectFromResult,
425
+ * });
426
+ *
427
+ * return (
428
+ * <div>
429
+ * <ul>
430
+ * {posts.map((post) => (
431
+ * <PostById key={post.id} id={post.id} />
432
+ * ))}
433
+ * </ul>
434
+ * </div>
435
+ * );
436
+ * }
437
+ * ```
438
+ *
439
+ * @template ResultType - The type of the result `data` returned by the query.
440
+ * @template QueryArgumentType - The type of the argument passed into the query.
441
+ * @template BaseQueryFunctionType - The type of the base query function being used.
442
+ * @template SelectedResultType - The type of the selected result returned by the __`selectFromResult`__ function.
443
+ *
444
+ * @since 2.3.0
445
+ * @public
446
+ */
447
+ export type TypedQueryStateSelector<
448
+ ResultType,
449
+ QueryArgumentType,
450
+ BaseQueryFunctionType extends BaseQueryFn,
451
+ SelectedResultType extends Record<string, any> = UseQueryStateDefaultResult<
452
+ QueryDefinition<QueryArgumentType, BaseQueryFunctionType, string, ResultType, string>
453
+ >,
454
+ > = QueryStateSelector<
455
+ SelectedResultType,
456
+ QueryDefinition<QueryArgumentType, BaseQueryFunctionType, string, ResultType, string>
457
+ >;
458
+
459
+ /**
460
+ * 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.
461
+ *
462
+ * Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).
463
+ *
464
+ * #### Features
465
+ *
466
+ * - Returns the latest request status and cached data from the Redux store
467
+ * - Re-renders as the request status changes and data becomes available
468
+ */
469
+ export type UseQueryState<D extends QueryDefinition<any, any, any, any>> = <
470
+ R extends Record<string, any> = UseQueryStateDefaultResult<D>,
471
+ >(
472
+ arg: QueryArgFrom<D> | SkipToken,
473
+ options?: UseQueryStateOptions<D, R>,
474
+ ) => UseQueryStateResult<D, R>;
475
+
476
+ export type TypedUseQueryState<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQueryState<
477
+ QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
478
+ >;
479
+
480
+ /**
481
+ * @internal
482
+ */
483
+ export type UseQueryStateOptions<
484
+ D extends QueryDefinition<any, any, any, any>,
485
+ R extends Record<string, any>,
486
+ > = {
487
+ /**
488
+ * Prevents a query from automatically running.
489
+ *
490
+ * @remarks
491
+ * When skip is true:
492
+ *
493
+ * - **If the query has cached data:**
494
+ * * 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
495
+ * * The query will have a status of `uninitialized`
496
+ * * If `skip: false` is set after skipping the initial load, the cached result will be used
497
+ * - **If the query does not have cached data:**
498
+ * * The query will have a status of `uninitialized`
499
+ * * The query will not exist in the state when viewed with the dev tools
500
+ * * The query will not automatically fetch on mount
501
+ * * The query will not automatically run when additional components with the same query are added that do run
502
+ *
503
+ * @example
504
+ * ```tsx
505
+ * // codeblock-meta title="Skip example"
506
+ * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
507
+ * const { data, error, status } = useGetPokemonByNameQuery(name, {
508
+ * skip,
509
+ * });
510
+ *
511
+ * return (
512
+ * <div>
513
+ * {name} - {status}
514
+ * </div>
515
+ * );
516
+ * };
517
+ * ```
518
+ */
519
+ skip?: boolean;
520
+ /**
521
+ * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.
522
+ * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.
523
+ * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
524
+ *
525
+ * @example
526
+ * ```tsx
527
+ * // codeblock-meta title="Using selectFromResult to extract a single result"
528
+ * function PostsList() {
529
+ * const { data: posts } = api.useGetPostsQuery();
530
+ *
531
+ * return (
532
+ * <ul>
533
+ * {posts?.data?.map((post) => (
534
+ * <PostById key={post.id} id={post.id} />
535
+ * ))}
536
+ * </ul>
537
+ * );
538
+ * }
539
+ *
540
+ * function PostById({ id }: { id: number }) {
541
+ * // Will select the post with the given id, and will only rerender if the given posts data changes
542
+ * const { post } = api.useGetPostsQuery(undefined, {
543
+ * selectFromResult: ({ data }) => ({
544
+ * post: data?.find((post) => post.id === id),
545
+ * }),
546
+ * });
547
+ *
548
+ * return <li>{post?.name}</li>;
549
+ * }
550
+ * ```
551
+ */
552
+ selectFromResult?: QueryStateSelector<R, D>;
553
+ };
554
+
555
+ /**
556
+ * Provides a way to define a "pre-typed" version of
557
+ * {@linkcode UseQueryStateOptions} with specific options for a given query.
558
+ * This is particularly useful for setting default query behaviors such as
559
+ * refetching strategies, which can be overridden as needed.
560
+ *
561
+ * @example
562
+ * <caption>#### __Create a `useQuery` hook with default options__</caption>
563
+ *
564
+ * ```ts
565
+ * import type {
566
+ * SubscriptionOptions,
567
+ * TypedUseQueryStateOptions,
568
+ * } from '@reduxjs/toolkit/query/react';
569
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
570
+ *
571
+ * type Post = {
572
+ * id: number;
573
+ * name: string;
574
+ * };
575
+ *
576
+ * const api = createApi({
577
+ * baseQuery: fetchBaseQuery({ baseUrl: '/' }),
578
+ * tagTypes: ['Post'],
579
+ * endpoints: (build) => ({
580
+ * getPosts: build.query<Post[], void>({
581
+ * query: () => 'posts',
582
+ * }),
583
+ * }),
584
+ * });
585
+ *
586
+ * const { useGetPostsQuery } = api;
587
+ *
588
+ * export const useGetPostsQueryWithDefaults = <
589
+ * SelectedResult extends Record<string, any>,
590
+ * >(
591
+ * overrideOptions: TypedUseQueryStateOptions<
592
+ * Post[],
593
+ * void,
594
+ * ReturnType<typeof fetchBaseQuery>,
595
+ * SelectedResult
596
+ * > &
597
+ * SubscriptionOptions,
598
+ * ) =>
599
+ * useGetPostsQuery(undefined, {
600
+ * // Insert default options here
601
+ *
602
+ * refetchOnMountOrArgChange: true,
603
+ * refetchOnFocus: true,
604
+ * ...overrideOptions,
605
+ * });
606
+ * ```
607
+ *
608
+ * @template ResultType - The type of the result `data` returned by the query.
609
+ * @template QueryArg - The type of the argument passed into the query.
610
+ * @template BaseQuery - The type of the base query function being used.
611
+ * @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.
612
+ *
613
+ * @since 2.2.8
614
+ * @public
615
+ */
616
+ export type TypedUseQueryStateOptions<
617
+ ResultType,
618
+ QueryArg,
619
+ BaseQuery extends BaseQueryFn,
620
+ SelectedResult extends Record<string, any> = UseQueryStateDefaultResult<
621
+ QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
622
+ >,
623
+ > = UseQueryStateOptions<
624
+ QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>,
625
+ SelectedResult
626
+ >;
627
+
628
+ export type UseQueryStateResult<_ extends QueryDefinition<any, any, any, any>, R> = R;
629
+
630
+ /**
631
+ * Helper type to manually type the result
632
+ * of the `useQueryState` hook in userland code.
633
+ */
634
+ export type TypedUseQueryStateResult<
635
+ ResultType,
636
+ QueryArg,
637
+ BaseQuery extends BaseQueryFn,
638
+ R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>,
639
+ > = R;
640
+
641
+ type UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> = QuerySubState<D> & {
642
+ /**
643
+ * Where `data` tries to hold data as much as possible, also reusing
644
+ * data from the last arguments passed into the hook, this property
645
+ * will always contain the received data from the query, for the current query arguments.
646
+ */
647
+ currentData?: ResultTypeFrom<D>;
648
+ /**
649
+ * Query has not started yet.
650
+ */
651
+ isUninitialized: false;
652
+ /**
653
+ * Query is currently loading for the first time. No data yet.
654
+ */
655
+ isLoading: false;
656
+ /**
657
+ * Query is currently fetching, but might have data from an earlier request.
658
+ */
659
+ isFetching: false;
660
+ /**
661
+ * Query has data from a successful load.
662
+ */
663
+ isSuccess: false;
664
+ /**
665
+ * Query is currently in "error" state.
666
+ */
667
+ isError: false;
668
+ };
669
+
670
+ type UseQueryStateUninitialized<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<
671
+ Extract<UseQueryStateBaseResult<D>, { status: QueryStatus.uninitialized }>,
672
+ { isUninitialized: true }
673
+ >;
674
+
675
+ type UseQueryStateLoading<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<
676
+ UseQueryStateBaseResult<D>,
677
+ { isLoading: true; isFetching: boolean; data: undefined }
678
+ >;
679
+
680
+ type UseQueryStateSuccessFetching<D extends QueryDefinition<any, any, any, any>> =
681
+ TSHelpersOverride<
682
+ UseQueryStateBaseResult<D>,
683
+ {
684
+ isSuccess: true;
685
+ isFetching: true;
686
+ error: undefined;
687
+ } & {
688
+ data: ResultTypeFrom<D>;
689
+ } & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>
690
+ >;
691
+
692
+ type UseQueryStateSuccessNotFetching<D extends QueryDefinition<any, any, any, any>> =
693
+ TSHelpersOverride<
694
+ UseQueryStateBaseResult<D>,
695
+ {
696
+ isSuccess: true;
697
+ isFetching: false;
698
+ error: undefined;
699
+ } & {
700
+ data: ResultTypeFrom<D>;
701
+ currentData: ResultTypeFrom<D>;
702
+ } & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>
703
+ >;
704
+
705
+ type UseQueryStateError<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<
706
+ UseQueryStateBaseResult<D>,
707
+ { isError: true } & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>
708
+ >;
709
+
710
+ type UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> = TSHelpersId<
711
+ | UseQueryStateUninitialized<D>
712
+ | UseQueryStateLoading<D>
713
+ | UseQueryStateSuccessFetching<D>
714
+ | UseQueryStateSuccessNotFetching<D>
715
+ | UseQueryStateError<D>
716
+ > & {
717
+ /**
718
+ * @deprecated Included for completeness, but discouraged.
719
+ * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
720
+ * and `isUninitialized` flags instead
721
+ */
722
+ status: QueryStatus;
723
+ };
724
+
725
+ export type LazyInfiniteQueryTrigger<D extends InfiniteQueryDefinition<any, any, any, any, any>> = {
726
+ /**
727
+ * Triggers a lazy query.
728
+ *
729
+ * By default, this will start a new request even if there is already a value in the cache.
730
+ * 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`.
731
+ *
732
+ * @remarks
733
+ * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
734
+ *
735
+ * @example
736
+ * ```ts
737
+ * // codeblock-meta title="Using .unwrap with async await"
738
+ * try {
739
+ * const payload = await getUserById(1).unwrap();
740
+ * console.log('fulfilled', payload);
741
+ * } catch (error) {
742
+ * console.error('rejected', error);
743
+ * }
744
+ * ```
745
+ */
746
+ (arg: QueryArgFrom<D>, direction: InfiniteQueryDirection): InfiniteQueryActionCreatorResult<D>;
747
+ };
748
+
749
+ export type TypedLazyInfiniteQueryTrigger<
750
+ ResultType,
751
+ QueryArg,
752
+ PageParam,
753
+ BaseQuery extends BaseQueryFn,
754
+ > = LazyInfiniteQueryTrigger<
755
+ InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>
756
+ >;
757
+
758
+ export type UseInfiniteQuerySubscriptionOptions<
759
+ D extends InfiniteQueryDefinition<any, any, any, any, any>,
760
+ > = SubscriptionOptions & {
761
+ /**
762
+ * Prevents a query from automatically running.
763
+ *
764
+ * @remarks
765
+ * When `skip` is true (or `skipToken` is passed in as `arg`):
766
+ *
767
+ * - **If the query has cached data:**
768
+ * * 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
769
+ * * The query will have a status of `uninitialized`
770
+ * * If `skip: false` is set after the initial load, the cached result will be used
771
+ * - **If the query does not have cached data:**
772
+ * * The query will have a status of `uninitialized`
773
+ * * The query will not exist in the state when viewed with the dev tools
774
+ * * The query will not automatically fetch on mount
775
+ * * The query will not automatically run when additional components with the same query are added that do run
776
+ *
777
+ * @example
778
+ * ```tsx
779
+ * // codeblock-meta no-transpile title="Skip example"
780
+ * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
781
+ * const { data, error, status } = useGetPokemonByNameQuery(name, {
782
+ * skip,
783
+ * });
784
+ *
785
+ * return (
786
+ * <div>
787
+ * {name} - {status}
788
+ * </div>
789
+ * );
790
+ * };
791
+ * ```
792
+ */
793
+ skip?: boolean;
794
+ /**
795
+ * 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.
796
+ * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
797
+ * - `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.
798
+ * - `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.
799
+ *
800
+ * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
801
+ */
802
+ refetchOnMountOrArgChange?: boolean | number;
803
+ initialPageParam?: PageParamFrom<D>;
804
+ /**
805
+ * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched
806
+ * (due to tag invalidation, polling, arg change configuration, or manual refetching),
807
+ * RTK Query will try to sequentially refetch all pages currently in the cache.
808
+ * When `false` only the first page will be refetched.
809
+ *
810
+ * This option applies to all automatic refetches for this subscription (polling, tag invalidation, etc.).
811
+ * It can be overridden on a per-call basis using the `refetch()` method.
812
+ */
813
+ refetchCachedPages?: boolean;
814
+ };
815
+
816
+ export type TypedUseInfiniteQuerySubscription<
817
+ ResultType,
818
+ QueryArg,
819
+ PageParam,
820
+ BaseQuery extends BaseQueryFn,
821
+ > = UseInfiniteQuerySubscription<
822
+ InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>
823
+ >;
824
+
825
+ export type UseInfiniteQuerySubscriptionResult<
826
+ D extends InfiniteQueryDefinition<any, any, any, any, any>,
827
+ > = {
828
+ refetch: (
829
+ options?: Pick<UseInfiniteQuerySubscriptionOptions<D>, 'refetchCachedPages'>,
830
+ ) => InfiniteQueryActionCreatorResult<D>;
831
+ trigger: LazyInfiniteQueryTrigger<D>;
832
+ fetchNextPage: () => InfiniteQueryActionCreatorResult<D>;
833
+ fetchPreviousPage: () => InfiniteQueryActionCreatorResult<D>;
834
+ };
835
+
836
+ /**
837
+ * Helper type to manually type the result
838
+ * of the `useQuerySubscription` hook in userland code.
839
+ */
840
+ export type TypedUseInfiniteQuerySubscriptionResult<
841
+ ResultType,
842
+ QueryArg,
843
+ PageParam,
844
+ BaseQuery extends BaseQueryFn,
845
+ > = UseInfiniteQuerySubscriptionResult<
846
+ InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>
847
+ >;
848
+
849
+ export type InfiniteQueryStateSelector<
850
+ R extends Record<string, any>,
851
+ D extends InfiniteQueryDefinition<any, any, any, any, any>,
852
+ > = (state: UseInfiniteQueryStateDefaultResult<D>) => R;
853
+
854
+ export type TypedInfiniteQueryStateSelector<
855
+ ResultType,
856
+ QueryArg,
857
+ PageParam,
858
+ BaseQuery extends BaseQueryFn,
859
+ SelectedResult extends Record<string, any> = UseInfiniteQueryStateDefaultResult<
860
+ InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>
861
+ >,
862
+ > = InfiniteQueryStateSelector<
863
+ SelectedResult,
864
+ InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>
865
+ >;
866
+
867
+ /**
868
+ * 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.
869
+ *
870
+ * 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.
871
+ *
872
+ * 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.
873
+ *
874
+ * This hook combines the functionality of both [`useInfiniteQueryState`](#useinfinitequerystate) and [`useInfiniteQuerySubscription`](#useinfinitequerysubscription) together, and is intended to be used in the majority of situations.
875
+ *
876
+ * As with normal query hooks, `skipToken` is a valid argument that will skip the query from executing.
877
+ *
878
+ * 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.
879
+ *
880
+ * 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.
881
+ *
882
+ *
883
+ * #### Features
884
+ *
885
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
886
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
887
+ * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards
888
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
889
+ * - Returns the latest request status and cached data from the Redux store
890
+ * - Re-renders as the request status changes and data becomes available
891
+ */
892
+ export type UseInfiniteQuery<D extends InfiniteQueryDefinition<any, any, any, any, any>> = <
893
+ R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>,
894
+ >(
895
+ arg: InfiniteQueryArgFrom<D> | SkipToken,
896
+ options?: UseInfiniteQuerySubscriptionOptions<D> & UseInfiniteQueryStateOptions<D, R>,
897
+ ) => UseInfiniteQueryHookResult<D, R> &
898
+ Pick<UseInfiniteQuerySubscriptionResult<D>, 'fetchNextPage' | 'fetchPreviousPage'>;
899
+
900
+ export type TypedUseInfiniteQuery<
901
+ ResultType,
902
+ QueryArg,
903
+ PageParam,
904
+ BaseQuery extends BaseQueryFn,
905
+ > = UseInfiniteQuery<
906
+ InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>
907
+ >;
908
+
909
+ /**
910
+ * 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.
911
+ *
912
+ * Note that this hook does not trigger fetching new data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQuerySubscription`](#useinfinitequerysubscription).
913
+ *
914
+ * #### Features
915
+ *
916
+ * - Returns the latest request status and cached data from the Redux store
917
+ * - Re-renders as the request status changes and data becomes available
918
+ */
919
+ export type UseInfiniteQueryState<D extends InfiniteQueryDefinition<any, any, any, any, any>> = <
920
+ R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>,
921
+ >(
922
+ arg: InfiniteQueryArgFrom<D> | SkipToken,
923
+ options?: UseInfiniteQueryStateOptions<D, R>,
924
+ ) => UseInfiniteQueryStateResult<D, R>;
925
+
926
+ export type TypedUseInfiniteQueryState<
927
+ ResultType,
928
+ QueryArg,
929
+ PageParam,
930
+ BaseQuery extends BaseQueryFn,
931
+ > = UseInfiniteQueryState<
932
+ InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>
933
+ >;
934
+
935
+ /**
936
+ * 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.
937
+ *
938
+ * 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.
939
+ *
940
+ * Note that this hook does not return a request status or cached data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQueryState`](#useinfinitequerystate).
941
+ *
942
+ * #### Features
943
+ *
944
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
945
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
946
+ * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards
947
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
948
+ */
949
+ export type UseInfiniteQuerySubscription<
950
+ D extends InfiniteQueryDefinition<any, any, any, any, any>,
951
+ > = (
952
+ arg: InfiniteQueryArgFrom<D> | SkipToken,
953
+ options?: UseInfiniteQuerySubscriptionOptions<D>,
954
+ ) => UseInfiniteQuerySubscriptionResult<D>;
955
+
956
+ export type UseInfiniteQueryHookResult<
957
+ D extends InfiniteQueryDefinition<any, any, any, any, any>,
958
+ R = UseInfiniteQueryStateDefaultResult<D>,
959
+ > = UseInfiniteQueryStateResult<D, R> &
960
+ Pick<UseInfiniteQuerySubscriptionResult<D>, 'refetch' | 'fetchNextPage' | 'fetchPreviousPage'>;
961
+
962
+ export type TypedUseInfiniteQueryHookResult<
963
+ ResultType,
964
+ QueryArg,
965
+ PageParam,
966
+ BaseQuery extends BaseQueryFn,
967
+ R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<
968
+ InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>
969
+ >,
970
+ > = UseInfiniteQueryHookResult<
971
+ InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>,
972
+ R
973
+ >;
974
+
975
+ export type UseInfiniteQueryStateOptions<
976
+ D extends InfiniteQueryDefinition<any, any, any, any, any>,
977
+ R extends Record<string, any>,
978
+ > = {
979
+ /**
980
+ * Prevents a query from automatically running.
981
+ *
982
+ * @remarks
983
+ * When skip is true:
984
+ *
985
+ * - **If the query has cached data:**
986
+ * * 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
987
+ * * The query will have a status of `uninitialized`
988
+ * * If `skip: false` is set after skipping the initial load, the cached result will be used
989
+ * - **If the query does not have cached data:**
990
+ * * The query will have a status of `uninitialized`
991
+ * * The query will not exist in the state when viewed with the dev tools
992
+ * * The query will not automatically fetch on mount
993
+ * * The query will not automatically run when additional components with the same query are added that do run
994
+ *
995
+ * @example
996
+ * ```tsx
997
+ * // codeblock-meta title="Skip example"
998
+ * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
999
+ * const { data, error, status } = useGetPokemonByNameQuery(name, {
1000
+ * skip,
1001
+ * });
1002
+ *
1003
+ * return (
1004
+ * <div>
1005
+ * {name} - {status}
1006
+ * </div>
1007
+ * );
1008
+ * };
1009
+ * ```
1010
+ */
1011
+ skip?: boolean;
1012
+ /**
1013
+ * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.
1014
+ * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.
1015
+ * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
1016
+ * Note that this should always return an object (not a primitive), as RTKQ adds fields to the return value.
1017
+ *
1018
+ * @example
1019
+ * ```tsx
1020
+ * // codeblock-meta title="Using selectFromResult to extract a single result"
1021
+ * function PostsList() {
1022
+ * const { data: posts } = api.useGetPostsQuery();
1023
+ *
1024
+ * return (
1025
+ * <ul>
1026
+ * {posts?.data?.map((post) => (
1027
+ * <PostById key={post.id} id={post.id} />
1028
+ * ))}
1029
+ * </ul>
1030
+ * );
1031
+ * }
1032
+ *
1033
+ * function PostById({ id }: { id: number }) {
1034
+ * // Will select the post with the given id, and will only rerender if the given posts data changes
1035
+ * const { post } = api.useGetPostsQuery(undefined, {
1036
+ * selectFromResult: ({ data }) => ({
1037
+ * post: data?.find((post) => post.id === id),
1038
+ * }),
1039
+ * });
1040
+ *
1041
+ * return <li>{post?.name}</li>;
1042
+ * }
1043
+ * ```
1044
+ */
1045
+ selectFromResult?: InfiniteQueryStateSelector<R, D>;
1046
+ };
1047
+
1048
+ export type TypedUseInfiniteQueryStateOptions<
1049
+ ResultType,
1050
+ QueryArg,
1051
+ PageParam,
1052
+ BaseQuery extends BaseQueryFn,
1053
+ SelectedResult extends Record<string, any> = UseInfiniteQueryStateDefaultResult<
1054
+ InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>
1055
+ >,
1056
+ > = UseInfiniteQueryStateOptions<
1057
+ InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>,
1058
+ SelectedResult
1059
+ >;
1060
+
1061
+ export type UseInfiniteQueryStateResult<
1062
+ D extends InfiniteQueryDefinition<any, any, any, any, any>,
1063
+ R = UseInfiniteQueryStateDefaultResult<D>,
1064
+ > = R;
1065
+
1066
+ export type TypedUseInfiniteQueryStateResult<
1067
+ ResultType,
1068
+ QueryArg,
1069
+ PageParam,
1070
+ BaseQuery extends BaseQueryFn,
1071
+ R = UseInfiniteQueryStateDefaultResult<
1072
+ InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>
1073
+ >,
1074
+ > = UseInfiniteQueryStateResult<
1075
+ InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>,
1076
+ R
1077
+ >;
1078
+
1079
+ type UseInfiniteQueryStateBaseResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> =
1080
+ InfiniteQuerySubState<D> & {
1081
+ /**
1082
+ * Where `data` tries to hold data as much as possible, also reusing
1083
+ * data from the last arguments passed into the hook, this property
1084
+ * will always contain the received data from the query, for the current query arguments.
1085
+ */
1086
+ currentData?: InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>;
1087
+ /**
1088
+ * Query has not started yet.
1089
+ */
1090
+ isUninitialized: false;
1091
+ /**
1092
+ * Query is currently loading for the first time. No data yet.
1093
+ */
1094
+ isLoading: false;
1095
+ /**
1096
+ * Query is currently fetching, but might have data from an earlier request.
1097
+ */
1098
+ isFetching: false;
1099
+ /**
1100
+ * Query has data from a successful load.
1101
+ */
1102
+ isSuccess: false;
1103
+ /**
1104
+ * Query is currently in "error" state.
1105
+ */
1106
+ isError: false;
1107
+ hasNextPage: boolean;
1108
+ hasPreviousPage: boolean;
1109
+ isFetchingNextPage: boolean;
1110
+ isFetchingPreviousPage: boolean;
1111
+ };
1112
+
1113
+ type UseInfiniteQueryStateDefaultResult<
1114
+ D extends InfiniteQueryDefinition<any, any, any, any, any>,
1115
+ > = TSHelpersId<
1116
+ | TSHelpersOverride<
1117
+ Extract<UseInfiniteQueryStateBaseResult<D>, { status: QueryStatus.uninitialized }>,
1118
+ { isUninitialized: true }
1119
+ >
1120
+ | TSHelpersOverride<
1121
+ UseInfiniteQueryStateBaseResult<D>,
1122
+ | { isLoading: true; isFetching: boolean; data: undefined }
1123
+ | ({
1124
+ isSuccess: true;
1125
+ isFetching: true;
1126
+ error: undefined;
1127
+ } & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp'>>)
1128
+ | ({
1129
+ isSuccess: true;
1130
+ isFetching: false;
1131
+ error: undefined;
1132
+ } & Required<
1133
+ Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp' | 'currentData'>
1134
+ >)
1135
+ | ({ isError: true } & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'error'>>)
1136
+ >
1137
+ > & {
1138
+ /**
1139
+ * @deprecated Included for completeness, but discouraged.
1140
+ * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
1141
+ * and `isUninitialized` flags instead
1142
+ */
1143
+ status: QueryStatus;
1144
+ };
1145
+
1146
+ export type MutationStateSelector<
1147
+ R extends Record<string, any>,
1148
+ D extends MutationDefinition<any, any, any, any>,
1149
+ > = (state: MutationResultSelectorResult<D>) => R;
1150
+
1151
+ export type UseMutationStateOptions<
1152
+ D extends MutationDefinition<any, any, any, any>,
1153
+ R extends Record<string, any>,
1154
+ > = {
1155
+ selectFromResult?: MutationStateSelector<R, D>;
1156
+ fixedCacheKey?: string;
1157
+ };
1158
+
1159
+ /**
1160
+ * Provides a way to define a "pre-typed" version of
1161
+ * {@linkcode UseMutationStateOptions} with specific options for a given mutation.
1162
+ *
1163
+ * @template ResultType - The type of the result `data` returned by the mutation.
1164
+ * @template QueryArg - The type of the argument passed into the mutation.
1165
+ * @template BaseQuery - The type of the base query function being used.
1166
+ * @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.
1167
+ *
1168
+ * @since 2.11.3
1169
+ * @public
1170
+ */
1171
+ export type TypedUseMutationStateOptions<
1172
+ ResultType,
1173
+ QueryArg,
1174
+ BaseQuery extends BaseQueryFn,
1175
+ SelectedResult extends Record<string, any> = MutationResultSelectorResult<
1176
+ MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>
1177
+ >,
1178
+ > = UseMutationStateOptions<
1179
+ MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>,
1180
+ SelectedResult
1181
+ >;
1182
+
1183
+ export type UseMutationStateResult<D extends MutationDefinition<any, any, any, any>, R> = R & {
1184
+ originalArgs?: QueryArgFrom<D>;
1185
+ /**
1186
+ * Resets the hook state to its initial `uninitialized` state.
1187
+ * This will also remove the last result from the cache.
1188
+ */
1189
+ reset: () => void;
1190
+ };
1191
+
1192
+ /**
1193
+ * Helper type to manually type the result
1194
+ * of the `useMutation` hook in userland code.
1195
+ */
1196
+ export type TypedUseMutationResult<
1197
+ ResultType,
1198
+ QueryArg,
1199
+ BaseQuery extends BaseQueryFn,
1200
+ R = MutationResultSelectorResult<
1201
+ MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>
1202
+ >,
1203
+ > = UseMutationStateResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;
1204
+
1205
+ /**
1206
+ * 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.
1207
+ *
1208
+ * #### Features
1209
+ *
1210
+ * - Manual control over firing a request to alter data on the server or possibly invalidate the cache
1211
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
1212
+ * - Returns the latest request status and cached data from the Redux store
1213
+ * - Re-renders as the request status changes and data becomes available
1214
+ */
1215
+ export type UseMutation<D extends MutationDefinition<any, any, any, any>> = <
1216
+ R extends Record<string, any> = MutationResultSelectorResult<D>,
1217
+ >(
1218
+ options?: UseMutationStateOptions<D, R>,
1219
+ ) => readonly [MutationTrigger<D>, UseMutationStateResult<D, R>];
1220
+
1221
+ export type TypedUseMutation<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseMutation<
1222
+ MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>
1223
+ >;
1224
+
1225
+ export type MutationTrigger<D extends MutationDefinition<any, any, any, any>> = {
1226
+ /**
1227
+ * Triggers the mutation and returns a Promise.
1228
+ * @remarks
1229
+ * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
1230
+ *
1231
+ * @example
1232
+ * ```ts
1233
+ * // codeblock-meta title="Using .unwrap with async await"
1234
+ * try {
1235
+ * const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
1236
+ * console.log('fulfilled', payload);
1237
+ * } catch (error) {
1238
+ * console.error('rejected', error);
1239
+ * }
1240
+ * ```
1241
+ */
1242
+ (arg: QueryArgFrom<D>): MutationActionCreatorResult<D>;
1243
+ };
1244
+
1245
+ export type TypedMutationTrigger<
1246
+ ResultType,
1247
+ QueryArg,
1248
+ BaseQuery extends BaseQueryFn,
1249
+ > = MutationTrigger<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
1250
+
1251
+ /**
1252
+ * Wrapper around `defaultQueryStateSelector` to be used in `useQuery`.
1253
+ * We want the initial render to already come back with
1254
+ * `{ isUninitialized: false, isFetching: true, isLoading: true }`
1255
+ * to prevent that the library user has to do an additional check for `isUninitialized`/
1256
+ */
1257
+ const noPendingQueryStateSelector: QueryStateSelector<any, any> = (selected) => {
1258
+ if (selected.isUninitialized) {
1259
+ return {
1260
+ ...selected,
1261
+ isUninitialized: false,
1262
+ isFetching: true,
1263
+ isLoading: selected.data !== undefined ? false : true,
1264
+ // This is the one place where we still have to use `QueryStatus` as an enum,
1265
+ // since it's the only reference in the React package and not in the core.
1266
+ status: QueryStatus.pending,
1267
+ } as any;
1268
+ }
1269
+ return selected;
1270
+ };
1271
+
1272
+ function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {
1273
+ const ret: any = {};
1274
+ keys.forEach((key) => {
1275
+ ret[key] = obj[key];
1276
+ });
1277
+ return ret;
1278
+ }
1279
+
1280
+ const COMMON_HOOK_DEBUG_FIELDS = [
1281
+ 'data',
1282
+ 'status',
1283
+ 'isLoading',
1284
+ 'isSuccess',
1285
+ 'isError',
1286
+ 'error',
1287
+ ] as const;
1288
+
1289
+ type GenericPrefetchThunk = (
1290
+ endpointName: any,
1291
+ arg: any,
1292
+ options: PrefetchOptions,
1293
+ ) => ThunkAction<void, any, any, UnknownAction>;
1294
+
1295
+ /**
1296
+ *
1297
+ * @param opts.api - An API with defined endpoints to create hooks for
1298
+ * @param opts.moduleOptions.batch - The version of the `batchedUpdates` function to be used
1299
+ * @param opts.moduleOptions.useDispatch - The version of the `useDispatch` hook to be used
1300
+ * @param opts.moduleOptions.useSelector - The version of the `useSelector` hook to be used
1301
+ * @returns An object containing functions to generate hooks based on an endpoint
1302
+ */
1303
+ export function buildHooks<Definitions extends EndpointDefinitions>({
1304
+ api,
1305
+ moduleOptions: {
1306
+ batch,
1307
+ hooks: { useDispatch, useSelector, useStore },
1308
+ unstable__sideEffectsInRender,
1309
+ createSelector,
1310
+ },
1311
+ serializeQueryArgs,
1312
+ context,
1313
+ }: {
1314
+ api: Api<any, Definitions, any, any, CoreModule>;
1315
+ moduleOptions: Required<ReactHooksModuleOptions>;
1316
+ serializeQueryArgs: SerializeQueryArgs<any>;
1317
+ context: ApiContext<Definitions>;
1318
+ }) {
1319
+ const usePossiblyImmediateEffect: (
1320
+ effect: () => void | undefined,
1321
+ deps?: DependencyList,
1322
+ ) => void = unstable__sideEffectsInRender ? (cb) => cb() : useEffect;
1323
+
1324
+ type UnsubscribePromiseRef = RefObject<{ unsubscribe?: () => void } | undefined>;
1325
+
1326
+ const unsubscribePromiseRef = (ref: UnsubscribePromiseRef) => ref.current?.unsubscribe?.();
1327
+
1328
+ const endpointDefinitions = context.endpointDefinitions;
1329
+
1330
+ return {
1331
+ buildQueryHooks,
1332
+ buildInfiniteQueryHooks,
1333
+ buildMutationHook,
1334
+ usePrefetch,
1335
+ };
1336
+
1337
+ function queryStatePreSelector(
1338
+ currentState: QueryResultSelectorResult<any>,
1339
+ lastResult: UseQueryStateDefaultResult<any> | undefined,
1340
+ queryArgs: any,
1341
+ ): UseQueryStateDefaultResult<any> {
1342
+ // if we had a last result and the current result is uninitialized,
1343
+ // we might have called `api.util.resetApiState`
1344
+ // in this case, reset the hook
1345
+ if (lastResult?.endpointName && currentState.isUninitialized) {
1346
+ const { endpointName } = lastResult;
1347
+ const endpointDefinition = endpointDefinitions[endpointName];
1348
+ if (
1349
+ queryArgs !== skipToken &&
1350
+ serializeQueryArgs({
1351
+ queryArgs: lastResult.originalArgs,
1352
+ endpointDefinition,
1353
+ endpointName,
1354
+ }) ===
1355
+ serializeQueryArgs({
1356
+ queryArgs,
1357
+ endpointDefinition,
1358
+ endpointName,
1359
+ })
1360
+ )
1361
+ lastResult = undefined;
1362
+ }
1363
+
1364
+ // data is the last known good request result we have tracked - or if none has been tracked yet the last good result for the current args
1365
+ let data = currentState.isSuccess ? currentState.data : lastResult?.data;
1366
+ if (data === undefined) data = currentState.data;
1367
+
1368
+ const hasData = data !== undefined;
1369
+
1370
+ // isFetching = true any time a request is in flight
1371
+ const isFetching = currentState.isLoading;
1372
+
1373
+ // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)
1374
+ const isLoading =
1375
+ (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;
1376
+
1377
+ // isSuccess = true when data is present and we're not refetching after an error.
1378
+ // That includes cases where the _current_ item is either actively
1379
+ // fetching or about to fetch due to an uninitialized entry.
1380
+ const isSuccess =
1381
+ currentState.isSuccess ||
1382
+ (hasData && ((isFetching && !lastResult?.isError) || currentState.isUninitialized));
1383
+
1384
+ return {
1385
+ ...currentState,
1386
+ data,
1387
+ currentData: currentState.data,
1388
+ isFetching,
1389
+ isLoading,
1390
+ isSuccess,
1391
+ } as UseQueryStateDefaultResult<any>;
1392
+ }
1393
+
1394
+ function infiniteQueryStatePreSelector(
1395
+ currentState: InfiniteQueryResultSelectorResult<any>,
1396
+ lastResult: UseInfiniteQueryStateDefaultResult<any> | undefined,
1397
+ queryArgs: any,
1398
+ ): UseInfiniteQueryStateDefaultResult<any> {
1399
+ // if we had a last result and the current result is uninitialized,
1400
+ // we might have called `api.util.resetApiState`
1401
+ // in this case, reset the hook
1402
+ if (lastResult?.endpointName && currentState.isUninitialized) {
1403
+ const { endpointName } = lastResult;
1404
+ const endpointDefinition = endpointDefinitions[endpointName];
1405
+ if (
1406
+ queryArgs !== skipToken &&
1407
+ serializeQueryArgs({
1408
+ queryArgs: lastResult.originalArgs,
1409
+ endpointDefinition,
1410
+ endpointName,
1411
+ }) ===
1412
+ serializeQueryArgs({
1413
+ queryArgs,
1414
+ endpointDefinition,
1415
+ endpointName,
1416
+ })
1417
+ )
1418
+ lastResult = undefined;
1419
+ }
1420
+
1421
+ // data is the last known good request result we have tracked - or if none has been tracked yet the last good result for the current args
1422
+ let data = currentState.isSuccess ? currentState.data : lastResult?.data;
1423
+ if (data === undefined) data = currentState.data;
1424
+
1425
+ const hasData = data !== undefined;
1426
+
1427
+ // isFetching = true any time a request is in flight
1428
+ const isFetching = currentState.isLoading;
1429
+ // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)
1430
+ const isLoading =
1431
+ (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching;
1432
+ // isSuccess = true when data is present and we're not refetching after an error.
1433
+ // That includes cases where the _current_ item is either actively
1434
+ // fetching or about to fetch due to an uninitialized entry.
1435
+ const isSuccess =
1436
+ currentState.isSuccess ||
1437
+ (hasData && ((isFetching && !lastResult?.isError) || currentState.isUninitialized));
1438
+
1439
+ return {
1440
+ ...currentState,
1441
+ data,
1442
+ currentData: currentState.data,
1443
+ isFetching,
1444
+ isLoading,
1445
+ isSuccess,
1446
+ } as UseInfiniteQueryStateDefaultResult<any>;
1447
+ }
1448
+
1449
+ function usePrefetch<EndpointName extends QueryKeys<Definitions>>(
1450
+ endpointName: EndpointName,
1451
+ defaultOptions?: PrefetchOptions,
1452
+ ) {
1453
+ const dispatch = useDispatch() as ThunkDispatch<any, any, UnknownAction>;
1454
+ const stableDefaultOptions = useShallowStableValue(defaultOptions);
1455
+
1456
+ return useCallback(
1457
+ (arg: any, options?: PrefetchOptions) =>
1458
+ dispatch(
1459
+ (api.util.prefetch as GenericPrefetchThunk)(endpointName, arg, {
1460
+ ...stableDefaultOptions,
1461
+ ...options,
1462
+ }),
1463
+ ),
1464
+ [endpointName, dispatch, stableDefaultOptions],
1465
+ );
1466
+ }
1467
+
1468
+ function useQuerySubscriptionCommonImpl<
1469
+ T extends QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>,
1470
+ >(
1471
+ endpointName: string,
1472
+ arg: unknown | SkipToken,
1473
+ {
1474
+ refetchOnReconnect,
1475
+ refetchOnFocus,
1476
+ refetchOnMountOrArgChange,
1477
+ skip = false,
1478
+ pollingInterval = 0,
1479
+ skipPollingIfUnfocused = false,
1480
+ ...rest
1481
+ }: UseQuerySubscriptionOptions = {},
1482
+ ) {
1483
+ const { initiate } = api.endpoints[endpointName] as ApiEndpointQuery<
1484
+ QueryDefinition<any, any, any, any, any>,
1485
+ Definitions
1486
+ >;
1487
+ const dispatch = useDispatch() as ThunkDispatch<any, any, UnknownAction>;
1488
+
1489
+ // TODO: Change this to `useRef<SubscriptionSelectors>(undefined)` after upgrading to React 19.
1490
+ const subscriptionSelectorsRef = useRef<SubscriptionSelectors | undefined>(undefined);
1491
+
1492
+ if (!subscriptionSelectorsRef.current) {
1493
+ const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
1494
+
1495
+ if (process.env.NODE_ENV !== 'production') {
1496
+ if (typeof returnedValue !== 'object' || typeof returnedValue?.type === 'string') {
1497
+ throw new Error(
1498
+ `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
1499
+ You must add the middleware for RTK-Query to function correctly!`,
1500
+ );
1501
+ }
1502
+ }
1503
+
1504
+ subscriptionSelectorsRef.current = returnedValue as unknown as SubscriptionSelectors;
1505
+ }
1506
+ const stableArg = useStableQueryArgs(skip ? skipToken : arg);
1507
+ const stableSubscriptionOptions = useShallowStableValue({
1508
+ refetchOnReconnect,
1509
+ refetchOnFocus,
1510
+ pollingInterval,
1511
+ skipPollingIfUnfocused,
1512
+ });
1513
+
1514
+ const initialPageParam = (rest as UseInfiniteQuerySubscriptionOptions<any>).initialPageParam;
1515
+ const stableInitialPageParam = useShallowStableValue(initialPageParam);
1516
+
1517
+ const refetchCachedPages = (rest as UseInfiniteQuerySubscriptionOptions<any>)
1518
+ .refetchCachedPages;
1519
+ const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages);
1520
+
1521
+ /**
1522
+ * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.
1523
+ */
1524
+ const promiseRef = useRef<T | undefined>(undefined);
1525
+
1526
+ let { queryCacheKey, requestId } = promiseRef.current || {};
1527
+
1528
+ // HACK We've saved the middleware subscription lookup callbacks into a ref,
1529
+ // so we can directly check here if the subscription exists for this query.
1530
+ let currentRenderHasSubscription = false;
1531
+ if (queryCacheKey && requestId) {
1532
+ currentRenderHasSubscription = subscriptionSelectorsRef.current.isRequestSubscribed(
1533
+ queryCacheKey,
1534
+ requestId,
1535
+ );
1536
+ }
1537
+
1538
+ const subscriptionRemoved = !currentRenderHasSubscription && promiseRef.current !== undefined;
1539
+
1540
+ usePossiblyImmediateEffect((): void | undefined => {
1541
+ if (subscriptionRemoved) {
1542
+ promiseRef.current = undefined;
1543
+ }
1544
+ }, [subscriptionRemoved]);
1545
+
1546
+ usePossiblyImmediateEffect((): void | undefined => {
1547
+ const lastPromise = promiseRef.current;
1548
+ if (typeof process !== 'undefined' && process.env.NODE_ENV === 'removeMeOnCompilation') {
1549
+ // this is only present to enforce the rule of hooks to keep `isSubscribed` in the dependency array
1550
+ console.log(subscriptionRemoved);
1551
+ }
1552
+
1553
+ if (stableArg === skipToken) {
1554
+ lastPromise?.unsubscribe();
1555
+ promiseRef.current = undefined;
1556
+ return;
1557
+ }
1558
+
1559
+ const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;
1560
+
1561
+ if (!lastPromise || lastPromise.arg !== stableArg) {
1562
+ lastPromise?.unsubscribe();
1563
+ const promise = dispatch(
1564
+ initiate(stableArg, {
1565
+ subscriptionOptions: stableSubscriptionOptions,
1566
+ forceRefetch: refetchOnMountOrArgChange,
1567
+ ...(isInfiniteQueryDefinition(endpointDefinitions[endpointName])
1568
+ ? {
1569
+ initialPageParam: stableInitialPageParam,
1570
+ refetchCachedPages: stableRefetchCachedPages,
1571
+ }
1572
+ : {}),
1573
+ }),
1574
+ );
1575
+
1576
+ promiseRef.current = promise as T;
1577
+ } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
1578
+ lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
1579
+ }
1580
+ }, [
1581
+ dispatch,
1582
+ initiate,
1583
+ refetchOnMountOrArgChange,
1584
+ stableArg,
1585
+ stableSubscriptionOptions,
1586
+ subscriptionRemoved,
1587
+ stableInitialPageParam,
1588
+ stableRefetchCachedPages,
1589
+ endpointName,
1590
+ ]);
1591
+
1592
+ return [promiseRef, dispatch, initiate, stableSubscriptionOptions] as const;
1593
+ }
1594
+
1595
+ function buildUseQueryState(
1596
+ endpointName: string,
1597
+ preSelector: typeof queryStatePreSelector | typeof infiniteQueryStatePreSelector,
1598
+ ) {
1599
+ const useQueryState = (
1600
+ arg: any,
1601
+ {
1602
+ skip = false,
1603
+ selectFromResult,
1604
+ }: UseQueryStateOptions<any, any> | UseInfiniteQueryStateOptions<any, any> = {},
1605
+ ) => {
1606
+ const { select } = api.endpoints[endpointName] as ApiEndpointQuery<
1607
+ QueryDefinition<any, any, any, any, any>,
1608
+ Definitions
1609
+ >;
1610
+ const stableArg = useStableQueryArgs(skip ? skipToken : arg);
1611
+
1612
+ type ApiRootState = Parameters<ReturnType<typeof select>>[0];
1613
+
1614
+ const lastValue = useRef<any>(undefined);
1615
+
1616
+ const selectDefaultResult: Selector<ApiRootState, any, [any]> = useMemo(
1617
+ () =>
1618
+ // Normally ts-ignores are bad and should be avoided, but we're
1619
+ // already casting this selector to be `Selector<any>` anyway,
1620
+ // so the inconsistencies don't matter here
1621
+ // @ts-ignore
1622
+ createSelector(
1623
+ [
1624
+ // @ts-ignore
1625
+ select(stableArg),
1626
+ (_: ApiRootState, lastResult: any) => lastResult,
1627
+ (_: ApiRootState) => stableArg,
1628
+ ],
1629
+ preSelector as any,
1630
+ {
1631
+ memoizeOptions: {
1632
+ resultEqualityCheck: shallowEqual,
1633
+ },
1634
+ },
1635
+ ),
1636
+ [select, stableArg],
1637
+ );
1638
+
1639
+ const querySelector: Selector<ApiRootState, any, [any]> = useMemo(
1640
+ () =>
1641
+ selectFromResult
1642
+ ? createSelector([selectDefaultResult], selectFromResult, {
1643
+ devModeChecks: { identityFunctionCheck: 'never' },
1644
+ })
1645
+ : selectDefaultResult,
1646
+ [selectDefaultResult, selectFromResult],
1647
+ );
1648
+
1649
+ const currentState = useSelector(
1650
+ (state: RootState<Definitions, any, any>) => querySelector(state, lastValue.current),
1651
+ shallowEqual,
1652
+ );
1653
+
1654
+ const store = useStore() as Store<RootState<Definitions, any, any>>;
1655
+ const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
1656
+ useIsomorphicLayoutEffect(() => {
1657
+ lastValue.current = newLastValue;
1658
+ }, [newLastValue]);
1659
+
1660
+ return currentState;
1661
+ };
1662
+
1663
+ return useQueryState;
1664
+ }
1665
+
1666
+ function usePromiseRefUnsubscribeOnUnmount(promiseRef: UnsubscribePromiseRef) {
1667
+ useEffect(() => {
1668
+ return () => {
1669
+ unsubscribePromiseRef(promiseRef);
1670
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1671
+ (promiseRef.current as any) = undefined;
1672
+ };
1673
+ }, [promiseRef]);
1674
+ }
1675
+
1676
+ function refetchOrErrorIfUnmounted<
1677
+ T extends QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>,
1678
+ >(promiseRef: RefObject<T | undefined>): T {
1679
+ if (!promiseRef.current)
1680
+ throw new Error('Cannot refetch a query that has not been started yet.');
1681
+ return promiseRef.current.refetch() as T;
1682
+ }
1683
+
1684
+ function buildQueryHooks(endpointName: string): QueryHooks<any> {
1685
+ const useQuerySubscription: UseQuerySubscription<any> = (arg: any, options = {}) => {
1686
+ const [promiseRef] = useQuerySubscriptionCommonImpl<QueryActionCreatorResult<any>>(
1687
+ endpointName,
1688
+ arg,
1689
+ options,
1690
+ );
1691
+
1692
+ usePromiseRefUnsubscribeOnUnmount(promiseRef);
1693
+
1694
+ return useMemo(
1695
+ () => ({
1696
+ /**
1697
+ * A method to manually refetch data for the query
1698
+ */
1699
+ refetch: () => refetchOrErrorIfUnmounted(promiseRef),
1700
+ }),
1701
+ [promiseRef],
1702
+ );
1703
+ };
1704
+
1705
+ const useLazyQuerySubscription: UseLazyQuerySubscription<any> = ({
1706
+ refetchOnReconnect,
1707
+ refetchOnFocus,
1708
+ pollingInterval = 0,
1709
+ skipPollingIfUnfocused = false,
1710
+ } = {}) => {
1711
+ const { initiate } = api.endpoints[endpointName] as ApiEndpointQuery<
1712
+ QueryDefinition<any, any, any, any, any>,
1713
+ Definitions
1714
+ >;
1715
+ const dispatch = useDispatch() as ThunkDispatch<any, any, UnknownAction>;
1716
+
1717
+ const [arg, setArg] = useState<any>(UNINITIALIZED_VALUE);
1718
+
1719
+ // TODO: Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.
1720
+ /**
1721
+ * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.
1722
+ */
1723
+ const promiseRef = useRef<QueryActionCreatorResult<any> | undefined>(undefined);
1724
+
1725
+ const stableSubscriptionOptions = useShallowStableValue({
1726
+ refetchOnReconnect,
1727
+ refetchOnFocus,
1728
+ pollingInterval,
1729
+ skipPollingIfUnfocused,
1730
+ });
1731
+
1732
+ usePossiblyImmediateEffect(() => {
1733
+ const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions;
1734
+
1735
+ if (stableSubscriptionOptions !== lastSubscriptionOptions) {
1736
+ promiseRef.current?.updateSubscriptionOptions(stableSubscriptionOptions);
1737
+ }
1738
+ }, [stableSubscriptionOptions]);
1739
+
1740
+ const subscriptionOptionsRef = useRef(stableSubscriptionOptions);
1741
+ usePossiblyImmediateEffect(() => {
1742
+ subscriptionOptionsRef.current = stableSubscriptionOptions;
1743
+ }, [stableSubscriptionOptions]);
1744
+
1745
+ const trigger = useCallback(
1746
+ function (arg: any, preferCacheValue = false) {
1747
+ let promise: QueryActionCreatorResult<any>;
1748
+
1749
+ batch(() => {
1750
+ unsubscribePromiseRef(promiseRef);
1751
+
1752
+ promiseRef.current = promise = dispatch(
1753
+ initiate(arg, {
1754
+ subscriptionOptions: subscriptionOptionsRef.current,
1755
+ forceRefetch: !preferCacheValue,
1756
+ }),
1757
+ );
1758
+
1759
+ setArg(arg);
1760
+ });
1761
+
1762
+ return promise!;
1763
+ },
1764
+ [dispatch, initiate],
1765
+ );
1766
+
1767
+ const reset = useCallback(() => {
1768
+ if (promiseRef.current?.queryCacheKey) {
1769
+ dispatch(
1770
+ api.internalActions.removeQueryResult({
1771
+ queryCacheKey: promiseRef.current?.queryCacheKey as QueryCacheKey,
1772
+ }),
1773
+ );
1774
+ }
1775
+ }, [dispatch]);
1776
+
1777
+ /* cleanup on unmount */
1778
+ useEffect(() => {
1779
+ return () => {
1780
+ unsubscribePromiseRef(promiseRef);
1781
+ };
1782
+ }, []);
1783
+
1784
+ /* if "cleanup on unmount" was triggered from a fast refresh, we want to reinstate the query */
1785
+ useEffect(() => {
1786
+ if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
1787
+ trigger(arg, true);
1788
+ }
1789
+ }, [arg, trigger]);
1790
+
1791
+ return useMemo(() => [trigger, arg, { reset }] as const, [trigger, arg, reset]);
1792
+ };
1793
+
1794
+ const useQueryState: UseQueryState<any> = buildUseQueryState(
1795
+ endpointName,
1796
+ queryStatePreSelector,
1797
+ );
1798
+
1799
+ return {
1800
+ useQueryState,
1801
+ useQuerySubscription,
1802
+ useLazyQuerySubscription,
1803
+ useLazyQuery(options) {
1804
+ const [trigger, arg, { reset }] = useLazyQuerySubscription(options);
1805
+ const queryStateResults = useQueryState(arg, {
1806
+ ...options,
1807
+ skip: arg === UNINITIALIZED_VALUE,
1808
+ });
1809
+
1810
+ const info = useMemo(() => ({ lastArg: arg }), [arg]);
1811
+ return useMemo(
1812
+ () => [trigger, { ...queryStateResults, reset }, info],
1813
+ [trigger, queryStateResults, reset, info],
1814
+ );
1815
+ },
1816
+ useQuery(arg, options) {
1817
+ const querySubscriptionResults = useQuerySubscription(arg, options);
1818
+ const queryStateResults = useQueryState(arg, {
1819
+ selectFromResult:
1820
+ arg === skipToken || options?.skip ? undefined : noPendingQueryStateSelector,
1821
+ ...options,
1822
+ });
1823
+
1824
+ const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS);
1825
+ useDebugValue(debugValue);
1826
+
1827
+ return useMemo(
1828
+ () => ({ ...queryStateResults, ...querySubscriptionResults }),
1829
+ [queryStateResults, querySubscriptionResults],
1830
+ );
1831
+ },
1832
+ };
1833
+ }
1834
+
1835
+ function buildInfiniteQueryHooks(endpointName: string): InfiniteQueryHooks<any> {
1836
+ const useInfiniteQuerySubscription: UseInfiniteQuerySubscription<any> = (
1837
+ arg: any,
1838
+ options = {},
1839
+ ) => {
1840
+ const [promiseRef, dispatch, initiate, stableSubscriptionOptions] =
1841
+ useQuerySubscriptionCommonImpl<InfiniteQueryActionCreatorResult<any>>(
1842
+ endpointName,
1843
+ arg,
1844
+ options,
1845
+ );
1846
+
1847
+ const subscriptionOptionsRef = useRef(stableSubscriptionOptions);
1848
+ usePossiblyImmediateEffect(() => {
1849
+ subscriptionOptionsRef.current = stableSubscriptionOptions;
1850
+ }, [stableSubscriptionOptions]);
1851
+
1852
+ // Extract and stabilize the hook-level refetchCachedPages option
1853
+ const hookRefetchCachedPages = (options as UseInfiniteQuerySubscriptionOptions<any>)
1854
+ .refetchCachedPages;
1855
+ const stableHookRefetchCachedPages = useShallowStableValue(hookRefetchCachedPages);
1856
+
1857
+ const trigger: LazyInfiniteQueryTrigger<any> = useCallback(
1858
+ function (arg: unknown, direction: 'forward' | 'backward') {
1859
+ let promise: InfiniteQueryActionCreatorResult<any>;
1860
+
1861
+ batch(() => {
1862
+ unsubscribePromiseRef(promiseRef);
1863
+
1864
+ promiseRef.current = promise = dispatch(
1865
+ (initiate as StartInfiniteQueryActionCreator<any>)(arg, {
1866
+ subscriptionOptions: subscriptionOptionsRef.current,
1867
+ direction,
1868
+ }),
1869
+ );
1870
+ });
1871
+
1872
+ return promise!;
1873
+ },
1874
+ [promiseRef, dispatch, initiate],
1875
+ );
1876
+
1877
+ usePromiseRefUnsubscribeOnUnmount(promiseRef);
1878
+
1879
+ const stableArg = useStableQueryArgs(options.skip ? skipToken : arg);
1880
+
1881
+ const refetch = useCallback(
1882
+ (options?: Pick<UseInfiniteQuerySubscriptionOptions<any>, 'refetchCachedPages'>) => {
1883
+ if (!promiseRef.current)
1884
+ throw new Error('Cannot refetch a query that has not been started yet.');
1885
+ // Merge per-call options with hook-level default
1886
+ const mergedOptions = {
1887
+ refetchCachedPages: options?.refetchCachedPages ?? stableHookRefetchCachedPages,
1888
+ };
1889
+ return promiseRef.current.refetch(mergedOptions);
1890
+ },
1891
+ [promiseRef, stableHookRefetchCachedPages],
1892
+ );
1893
+
1894
+ return useMemo(() => {
1895
+ const fetchNextPage = () => {
1896
+ return trigger(stableArg, 'forward');
1897
+ };
1898
+
1899
+ const fetchPreviousPage = () => {
1900
+ return trigger(stableArg, 'backward');
1901
+ };
1902
+
1903
+ return {
1904
+ trigger,
1905
+ /**
1906
+ * A method to manually refetch data for the query
1907
+ */
1908
+ refetch,
1909
+ fetchNextPage,
1910
+ fetchPreviousPage,
1911
+ };
1912
+ }, [refetch, trigger, stableArg]);
1913
+ };
1914
+
1915
+ const useInfiniteQueryState: UseInfiniteQueryState<any> = buildUseQueryState(
1916
+ endpointName,
1917
+ infiniteQueryStatePreSelector,
1918
+ );
1919
+
1920
+ return {
1921
+ useInfiniteQueryState,
1922
+ useInfiniteQuerySubscription,
1923
+ useInfiniteQuery(arg, options) {
1924
+ const { refetch, fetchNextPage, fetchPreviousPage } = useInfiniteQuerySubscription(
1925
+ arg,
1926
+ options,
1927
+ );
1928
+ const queryStateResults = useInfiniteQueryState(arg, {
1929
+ selectFromResult:
1930
+ arg === skipToken || options?.skip ? undefined : noPendingQueryStateSelector,
1931
+ ...options,
1932
+ });
1933
+
1934
+ const debugValue = pick(
1935
+ queryStateResults,
1936
+ ...COMMON_HOOK_DEBUG_FIELDS,
1937
+ 'hasNextPage',
1938
+ 'hasPreviousPage',
1939
+ );
1940
+ useDebugValue(debugValue);
1941
+
1942
+ return useMemo(
1943
+ () => ({
1944
+ ...queryStateResults,
1945
+ fetchNextPage,
1946
+ fetchPreviousPage,
1947
+ refetch,
1948
+ }),
1949
+ [queryStateResults, fetchNextPage, fetchPreviousPage, refetch],
1950
+ );
1951
+ },
1952
+ };
1953
+ }
1954
+
1955
+ function buildMutationHook(name: string): UseMutation<any> {
1956
+ return ({ selectFromResult, fixedCacheKey } = {}) => {
1957
+ const { select, initiate } = api.endpoints[name] as ApiEndpointMutation<
1958
+ MutationDefinition<any, any, any, any, any>,
1959
+ Definitions
1960
+ >;
1961
+ const dispatch = useDispatch() as ThunkDispatch<any, any, UnknownAction>;
1962
+ const [promise, setPromise] = useState<MutationActionCreatorResult<any>>();
1963
+
1964
+ useEffect(
1965
+ () => () => {
1966
+ if (!promise?.arg.fixedCacheKey) {
1967
+ promise?.reset();
1968
+ }
1969
+ },
1970
+ [promise],
1971
+ );
1972
+
1973
+ const triggerMutation = useCallback(
1974
+ function (arg: Parameters<typeof initiate>['0']) {
1975
+ const promise = dispatch(initiate(arg, { fixedCacheKey }));
1976
+ setPromise(promise);
1977
+ return promise;
1978
+ },
1979
+ [dispatch, initiate, fixedCacheKey],
1980
+ );
1981
+
1982
+ const { requestId } = promise || {};
1983
+ const selectDefaultResult = useMemo(
1984
+ () => select({ fixedCacheKey, requestId: promise?.requestId }),
1985
+ [fixedCacheKey, promise, select],
1986
+ );
1987
+ const mutationSelector = useMemo(
1988
+ (): Selector<RootState<Definitions, any, any>, any> =>
1989
+ selectFromResult
1990
+ ? createSelector([selectDefaultResult], selectFromResult)
1991
+ : selectDefaultResult,
1992
+ [selectFromResult, selectDefaultResult],
1993
+ );
1994
+
1995
+ const currentState = useSelector(mutationSelector, shallowEqual);
1996
+ const originalArgs = fixedCacheKey == null ? promise?.arg.originalArgs : undefined;
1997
+ const reset = useCallback(() => {
1998
+ batch(() => {
1999
+ if (promise) {
2000
+ setPromise(undefined);
2001
+ }
2002
+ if (fixedCacheKey) {
2003
+ dispatch(
2004
+ api.internalActions.removeMutationResult({
2005
+ requestId,
2006
+ fixedCacheKey,
2007
+ }),
2008
+ );
2009
+ }
2010
+ });
2011
+ }, [dispatch, fixedCacheKey, promise, requestId]);
2012
+
2013
+ const debugValue = pick(currentState, ...COMMON_HOOK_DEBUG_FIELDS, 'endpointName');
2014
+ useDebugValue(debugValue);
2015
+
2016
+ const finalState = useMemo(
2017
+ () => ({ ...currentState, originalArgs, reset }),
2018
+ [currentState, originalArgs, reset],
2019
+ );
2020
+
2021
+ return useMemo(() => [triggerMutation, finalState] as const, [triggerMutation, finalState]);
2022
+ };
2023
+ }
2024
+ }