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