Open History to see the last commit
1'use client'
2import * as React from 'react'
3β
4import { notifyManager, replaceEqualDeep } from '@tanstack/query-core'
5import { useQueryClient } from './QueryClientProvider'
6import type {
7 Mutation,
8 MutationCache,
9 MutationFilters,
10 MutationState,
11 QueryClient,
12} from '@tanstack/query-core'
13β
14/**
15 * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`
16 * (useful for app-wide loading indicators).
17 *
18 * @param filters - The {@link MutationFilters} to narrow down the matched mutations.
19 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
20 * be used.
21 * @returns Will be the `number` of the mutations that your application currently has `pending`.
22 *
23 * @example
24 * ```tsx
25 * import { useIsMutating } from '@tanstack/react-query'
26 *
27 * function PostsMutatingIndicator() {
28 * // How many mutations matching the posts prefix are in progress?
29 * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
30 *
31 * return isMutatingPosts ? <span>Saving posts...</span> : null
32 * }
33 * ```
34 */
35export function useIsMutating(
36 filters?: MutationFilters,
37 queryClient?: QueryClient,
38): number {
39 const client = useQueryClient(queryClient)
40 return useMutationState(
41 { filters: { ...filters, status: 'pending' } },
42 client,
43 ).length
44}
45β
46type MutationTypeFromResult<TResult> = [TResult] extends [
47 MutationState<
48 infer TData,
49 infer TError,
50 infer TVariables,
51 infer TOnMutateResult
52 >,
53]
54 ? Mutation<TData, TError, TVariables, TOnMutateResult>
55 : Mutation
56β
57type MutationStateOptions<
58 TResult = MutationState,
59 TMutation extends Mutation<any, any, any, any> =
60 MutationTypeFromResult<TResult>,
61> = {
62 filters?: MutationFilters
63 select?: (mutation: TMutation) => TResult
64}
65β
66function getResult<
67 TResult = MutationState,
68 TMutation extends Mutation<any, any, any, any> =
69 MutationTypeFromResult<TResult>,
70>(
71 mutationCache: MutationCache,
72 options: MutationStateOptions<TResult, TMutation>,
73): Array<TResult> {
74 return mutationCache
75 .findAll(options.filters)
76 .map(
77 (mutation): TResult =>
78 (options.select
79 ? options.select(mutation as TMutation)
80 : mutation.state) as TResult,
81 )
82}
83β
84/**
85 * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass
86 * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation
87 * state.
88 *
89 * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the
90 * mutation state.
91 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
92 * be used.
93 * @returns Will be an Array of whatever `select` returns for each matching mutation.
94 *
95 * @example
96 * Get all variables of all running mutations:
97 * ```tsx
98 * import { useMutationState } from '@tanstack/react-query'
99 *
100 * function PendingPosts() {
101 * const pendingVariables = useMutationState({
102 * filters: { status: 'pending' },
103 * select: (mutation) => mutation.state.variables,
104 * })
105 *
106 * return <>{pendingVariables.length} posts saving...</>
107 * }
108 * ```
109 *
110 * @example
111 * Get all data for specific mutations via the `mutationKey`:
112 * ```tsx
113 * import { useMutation, useMutationState } from '@tanstack/react-query'
114 *
115 * const mutationKey = ['posts']
116 *
117 * function Posts() {
118 * // Some mutation that we want to get the state for
119 * const mutation = useMutation({
120 * mutationKey,
121 * mutationFn: createPosts,
122 * })
123 *
124 * const savedPosts = useMutationState({
125 * // this mutation key needs to match the mutation key of the given mutation (see above)
126 * filters: { mutationKey, status: 'success' },
127 * select: (mutation) => mutation.state.data,
128 * })
129 *
130 * return (
131 * <button onClick={() => mutation.mutate(['New Post'])}>
132 * Create post ({savedPosts.length} saved so far)
133 * </button>
134 * )
135 * }
136 * ```
137 *
138 * @example
139 * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
140 * entry to the mutation cache for `gcTime` milliseconds β with the `status: 'success'` filter below, check the
141 * last item that `useMutationState` returns to get the latest successful invocation:
142 * ```tsx
143 * import { useMutationState } from '@tanstack/react-query'
144 *
145 * function LatestPost() {
146 * const savedPosts = useMutationState({
147 * filters: { mutationKey: ['posts'], status: 'success' },
148 * select: (mutation) => mutation.state.data,
149 * })
150 *
151 * const latestSavedPost = savedPosts[savedPosts.length - 1]
152 *
153 * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>
154 * }
155 * ```
156 */
157export function useMutationState<
158 TResult = MutationState,
159 TMutation extends Mutation<any, any, any, any> =
160 MutationTypeFromResult<TResult>,
161>(
162 options: MutationStateOptions<TResult, TMutation> = {},
163 queryClient?: QueryClient,
164): Array<TResult> {
165 const mutationCache = useQueryClient(queryClient).getMutationCache()
166 const optionsRef = React.useRef(options)
167 const result = React.useRef<Array<TResult>>(null)
168 if (result.current === null) {
169 result.current = getResult(mutationCache, options)
170 }
171β
172 React.useEffect(() => {
173 optionsRef.current = options
174 })
175β
176 return React.useSyncExternalStore(
177 React.useCallback(
178 (onStoreChange) =>
179 mutationCache.subscribe(() => {
180 const nextResult = replaceEqualDeep(
181 result.current,
182 getResult(mutationCache, optionsRef.current),
183 )
184 if (result.current !== nextResult) {
185 result.current = nextResult
186 notifyManager.schedule(onStoreChange)
187 }
188 }),
189 [mutationCache],
190 ),
191 () => result.current,
192 () => result.current,
193 )!
194}