Open History to see the last commit
1import { createEffect, createMemo, createSignal, onCleanup } from 'solid-js'
2import { useQueryClientResolver } from './QueryClientProvider'
3import type { MutationFilters } from '@tanstack/query-core'
4import type { QueryClient } from './QueryClient'
5import type { Accessor } from 'solid-js'
6β
7/**
8 * The `useIsMutating` primitive returns the `number` of mutations that your application currently has `pending`
9 * (useful for app-wide loading indicators).
10 *
11 * @param filters - An accessor returning the {@link MutationFilters} to narrow down the matched mutations.
12 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
13 * will be used.
14 * @returns An accessor for the `number` of the mutations that your application currently has `pending`.
15 *
16 * @example
17 * ```tsx
18 * import { useIsMutating } from '@tanstack/solid-query'
19 *
20 * function PostsMutatingIndicator() {
21 * // How many mutations matching the posts prefix are in progress?
22 * const isMutatingPosts = useIsMutating(() => ({ mutationKey: ['posts'] }))
23 *
24 * return isMutatingPosts() > 0 ? <span>Saving posts...</span> : null
25 * }
26 * ```
27 */
28export function useIsMutating(
29 filters?: Accessor<MutationFilters>,
30 queryClient?: Accessor<QueryClient>,
31): Accessor<number> {
32 const resolveClient = useQueryClientResolver(queryClient)
33 const client = createMemo(() => resolveClient())
34 const mutationCache = createMemo(() => client().getMutationCache())
35β
36 const [mutations, setMutations] = createSignal(
37 client().isMutating(filters?.()),
38 )
39β
40 createEffect(() => {
41 setMutations(client().isMutating(filters?.()))
42β
43 const unsubscribe = mutationCache().subscribe(() => {
44 setMutations(client().isMutating(filters?.()))
45 })
46β
47 onCleanup(unsubscribe)
48 })
49β
50 return mutations
51}