Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useMutationState.ts

205 lines6.3 KB

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