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