Open History to see the last commit
1import {
2 computed,
3 getCurrentScope,
4 onScopeDispose,
5 shallowReadonly,
6 shallowRef,
7 watch,
8} from 'vue-demi'
9import { useQueryClient } from './useQueryClient'
10import { cloneDeepUnref } from './utils'
11import type {
12 Mutation,
13 MutationFilters,
14 MutationState,
15} from '@tanstack/query-core'
16import type { Ref } from 'vue-demi'
17import type { MutationCache } from './mutationCache'
18import type { QueryClient } from './queryClient'
19import type { MaybeRefDeep } from './types'
20β
21type VueMutationFilters = MaybeRefDeep<MutationFilters>
22β
23/**
24 * The filters accepted by `useIsMutating`: {@link MutationFilters} as a plain object, a `ref`, or a reactive
25 * getter.
26 */
27export type UseIsMutatingFilters =
28 | MaybeRefDeep<Omit<MutationFilters, 'status'>>
29 | (() => MaybeRefDeep<Omit<MutationFilters, 'status'>>)
30β
31/**
32 * The `useIsMutating` composable returns a `ref` to the `number` of mutations that your application currently
33 * has `pending` (useful for app-wide loading indicators).
34 *
35 * `filters` may be a plain object, `MaybeRefDeep`, or a reactive getter (`() => ({ ... })`) β pass a getter if
36 * the filters themselves depend on other reactive state.
37 * @param filters - The {@link MutationFilters} to narrow down the matched mutations.
38 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
39 * will be used.
40 * @returns A `ref` to the `number` of the mutations that your application currently has `pending`.
41 * @example
42 * ```vue
43 * <script setup lang="ts">
44 * import { useIsMutating } from '@tanstack/vue-query'
45 *
46 * // How many mutations matching the posts prefix are in progress?
47 * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
48 * </script>
49 *
50 * <template>
51 * <span v-if="isMutatingPosts">Saving posts...</span>
52 * </template>
53 * ```
54 */
55export function useIsMutating(
56 filters: UseIsMutatingFilters = {},
57 queryClient?: QueryClient,
58): Ref<number> {
59 if (process.env.NODE_ENV === 'development') {
60 if (!getCurrentScope()) {
61 console.warn(
62 'vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.',
63 )
64 }
65 }
66β
67 const client = queryClient || useQueryClient()
68β
69 const mutationState = useMutationState(
70 {
71 filters: computed(() => ({
72 ...cloneDeepUnref(typeof filters === 'function' ? filters() : filters),
73 status: 'pending' as const,
74 })),
75 },
76 client,
77 )
78 const length = computed(() => mutationState.value.length)
79β
80 return length
81}
82β
83type MutationTypeFromResult<TResult> = [TResult] extends [
84 MutationState<
85 infer TData,
86 infer TError,
87 infer TVariables,
88 infer TOnMutateResult
89 >,
90]
91 ? Mutation<TData, TError, TVariables, TOnMutateResult>
92 : Mutation
93β
94/**
95 * The options accepted by `useMutationState`: the `filters` matching the mutations, and `select` to map each
96 * one (to its state, by default).
97 */
98export type MutationStateOptions<
99 TResult = MutationState,
100 TMutation extends Mutation<any, any, any, any> =
101 MutationTypeFromResult<TResult>,
102> = {
103 /**
104 * The filters that select the mutations to return the state of.
105 */
106 filters?: VueMutationFilters
107 /**
108 * Maps each matching mutation to the value returned for it. Defaults to the mutation's `state`.
109 */
110 select?: (mutation: TMutation) => TResult
111}
112β
113/**
114 * Collects the mutations in the cache that match `options.filters`, mapped with `options.select`
115 * (or to their state, by default).
116 * @param mutationCache - The mutation cache to read.
117 * @param options - The `filters` to match and the `select` function to map each mutation with.
118 * @returns The selected value of every matching mutation.
119 */
120function getResult<
121 TResult = MutationState,
122 TMutation extends Mutation<any, any, any, any> =
123 MutationTypeFromResult<TResult>,
124>(
125 mutationCache: MutationCache,
126 options: MutationStateOptions<TResult, TMutation>,
127): Array<TResult> {
128 return mutationCache
129 .findAll(options.filters)
130 .map(
131 (mutation): TResult =>
132 (options.select
133 ? options.select(mutation as TMutation)
134 : mutation.state) as TResult,
135 )
136}
137β
138/**
139 * `useMutationState` is a composable that gives you access to all mutations in the `MutationCache`. You can
140 * pass `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the
141 * mutation state.
142 *
143 * `options` may be a plain object or a reactive getter (`() => ({ ... })`) β pass a getter if the filters
144 * themselves depend on other reactive state.
145 * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the
146 * mutation state.
147 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
148 * will be used.
149 * @returns A `ref` to an Array of whatever `select` returns for each matching mutation.
150 * @example
151 * Get all variables of all running mutations:
152 * ```vue
153 * <script setup lang="ts">
154 * import { useMutationState } from '@tanstack/vue-query'
155 *
156 * const pendingVariables = useMutationState({
157 * filters: { status: 'pending' },
158 * select: (mutation) => mutation.state.variables,
159 * })
160 * </script>
161 *
162 * <template>{{ pendingVariables.length }} posts saving...</template>
163 * ```
164 * @example
165 * Get all data for specific mutations via the `mutationKey`:
166 * ```vue
167 * <script setup lang="ts">
168 * import { useMutation, useMutationState } from '@tanstack/vue-query'
169 *
170 * const mutationKey = ['posts']
171 *
172 * // Some mutation that we want to get the state for
173 * const mutation = useMutation({
174 * mutationKey,
175 * mutationFn: createPosts,
176 * })
177 *
178 * const savedPosts = useMutationState({
179 * // this mutation key needs to match the mutation key of the given mutation (see above)
180 * filters: { mutationKey, status: 'success' },
181 * select: (mutation) => mutation.state.data,
182 * })
183 * </script>
184 *
185 * <template>
186 * <button @click="mutation.mutate(['New Post'])">
187 * Create post ({{ savedPosts.length }} saved so far)
188 * </button>
189 * </template>
190 * ```
191 * @example
192 * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
193 * entry to the mutation cache for `gcTime` milliseconds β with the `status: 'success'` filter below, check the
194 * last item that `useMutationState` returns to get the latest successful invocation:
195 * ```vue
196 * <script setup lang="ts">
197 * import { computed } from 'vue'
198 * import { useMutationState } from '@tanstack/vue-query'
199 *
200 * const savedPosts = useMutationState({
201 * filters: { mutationKey: ['posts'], status: 'success' },
202 * select: (mutation) => mutation.state.data,
203 * })
204 *
205 * const latestSavedPost = computed(() => savedPosts.value[savedPosts.value.length - 1])
206 * </script>
207 *
208 * <template>{{ latestSavedPost ? 'Saved' : 'Nothing saved yet' }}</template>
209 * ```
210 */
211export function useMutationState<
212 TResult = MutationState,
213 TMutation extends Mutation<any, any, any, any> =
214 MutationTypeFromResult<TResult>,
215>(
216 options:
217 | MutationStateOptions<TResult, TMutation>
218 | (() => MutationStateOptions<TResult, TMutation>) = {},
219 queryClient?: QueryClient,
220): Readonly<Ref<Array<TResult>>> {
221 const resolvedOptions = computed(() => {
222 const newOptions = typeof options === 'function' ? options() : options
223 return {
224 filters: cloneDeepUnref(newOptions.filters),
225 select: newOptions.select,
226 }
227 })
228 const mutationCache = (queryClient || useQueryClient()).getMutationCache()
229 const state = shallowRef(getResult(mutationCache, resolvedOptions.value))
230 const unsubscribe = mutationCache.subscribe(() => {
231 state.value = getResult(mutationCache, resolvedOptions.value)
232 })
233β
234 watch(resolvedOptions, () => {
235 state.value = getResult(mutationCache, resolvedOptions.value)
236 })
237β
238 onScopeDispose(() => {
239 unsubscribe()
240 })
241β
242 return shallowReadonly(state)
243}