Open History to see the last commit
1import { notifyManager, replaceEqualDeep } from '@tanstack/query-core'
2import { useCallback, useEffect, useRef } from 'preact/hooks'
3β
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?: MutationFilters,
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 * Collects the mutations in the cache that match `options.filters`, mapped with `options.select`
66 * (or to their state, by default).
67 * @param mutationCache - The mutation cache to read.
68 * @param options - The `filters` to match and the `select` function to map each mutation with.
69 * @returns The selected value of every matching mutation.
70 */
71function getResult<
72 TResult = MutationState,
73 TMutation extends Mutation<any, any, any, any> =
74 MutationTypeFromResult<TResult>,
75>(
76 mutationCache: MutationCache,
77 options: MutationStateOptions<TResult, TMutation>,
78): Array<TResult> {
79 return mutationCache
80 .findAll(options.filters)
81 .map(
82 (mutation): TResult =>
83 (options.select
84 ? options.select(mutation as TMutation)
85 : mutation.state) as TResult,
86 )
87}
88β
89/**
90 * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass
91 * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation
92 * state.
93 * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the
94 * mutation state.
95 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
96 * be used.
97 * @returns Will be an Array of whatever `select` returns for each matching mutation.
98 * @example
99 * Get all variables of all running mutations:
100 * ```tsx
101 * import { useMutationState } from '@tanstack/preact-query'
102 *
103 * function PendingPosts() {
104 * const pendingVariables = useMutationState({
105 * filters: { status: 'pending' },
106 * select: (mutation) => mutation.state.variables,
107 * })
108 *
109 * return <>{pendingVariables.length} posts saving...</>
110 * }
111 * ```
112 * @example
113 * Get all data for specific mutations via the `mutationKey`:
114 * ```tsx
115 * import { useMutation, useMutationState } from '@tanstack/preact-query'
116 *
117 * const mutationKey = ['posts']
118 *
119 * function Posts() {
120 * // Some mutation that we want to get the state for
121 * const mutation = useMutation({
122 * mutationKey,
123 * mutationFn: createPosts,
124 * })
125 *
126 * const savedPosts = useMutationState({
127 * // this mutation key needs to match the mutation key of the given mutation (see above)
128 * filters: { mutationKey, status: 'success' },
129 * select: (mutation) => mutation.state.data,
130 * })
131 *
132 * return (
133 * <button onClick={() => mutation.mutate(['New Post'])}>
134 * Create post ({savedPosts.length} saved so far)
135 * </button>
136 * )
137 * }
138 * ```
139 * @example
140 * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
141 * entry to the mutation cache for `gcTime` milliseconds β with the `status: 'success'` filter below, check the
142 * last item that `useMutationState` returns to get the latest successful invocation:
143 * ```tsx
144 * import { useMutationState } from '@tanstack/preact-query'
145 *
146 * function LatestPost() {
147 * const savedPosts = useMutationState({
148 * filters: { mutationKey: ['posts'], status: 'success' },
149 * select: (mutation) => mutation.state.data,
150 * })
151 *
152 * const latestSavedPost = savedPosts[savedPosts.length - 1]
153 *
154 * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>
155 * }
156 * ```
157 */
158export function useMutationState<
159 TResult = MutationState,
160 TMutation extends Mutation<any, any, any, any> =
161 MutationTypeFromResult<TResult>,
162>(
163 options: MutationStateOptions<TResult, TMutation> = {},
164 queryClient?: QueryClient,
165): Array<TResult> {
166 const mutationCache = useQueryClient(queryClient).getMutationCache()
167 const optionsRef = useRef(options)
168 const resultRef = useRef<Array<TResult>>(null)
169 if (resultRef.current === null) {
170 resultRef.current = getResult(mutationCache, options)
171 }
172β
173 useEffect(() => {
174 optionsRef.current = options
175 })
176β
177 return useSyncExternalStore(
178 useCallback(
179 (onStoreChange) =>
180 mutationCache.subscribe(() => {
181 const nextResult = replaceEqualDeep(
182 resultRef.current,
183 getResult(mutationCache, optionsRef.current),
184 )
185 if (resultRef.current !== nextResult) {
186 resultRef.current = nextResult
187 notifyManager.schedule(onStoreChange)
188 }
189 }),
190 [mutationCache],
191 ),
192 () => resultRef.current,
193 )!
194}