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

useMutationState.ts

242 lines7.7 KB

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