Debian Codegraph @

install/freeipa-webui/node_modules/@reduxjs/toolkit/src/query/react/buildHooks.ts

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