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