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