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

useMutationState.ts

49 lines1.3 KB

1import { readable } from 'svelte/store'
2import { notifyManager, replaceEqualDeep } from '@tanstack/query-core'
3import { useQueryClient } from './useQueryClient.js'
4import type {
5 MutationCache,
6 MutationState,
7 QueryClient,
8} from '@tanstack/query-core'
9import type { Readable } from 'svelte/store'
10import type { MutationStateOptions } from './types.js'
11​
12function getResult<TResult = MutationState>(
13 mutationCache: MutationCache,
14 options: MutationStateOptions<TResult>,
15): Array<TResult> {
16 return mutationCache
17 .findAll(options.filters)
18 .map(
19 (mutation): TResult =>
20 (options.select ? options.select(mutation) : mutation.state) as TResult,
21 )
23​
24export function useMutationState<TResult = MutationState>(
25 options: MutationStateOptions<TResult> = {},
26 queryClient?: QueryClient,
27): Readable<Array<TResult>> {
28 const client = useQueryClient(queryClient)
29 const mutationCache = client.getMutationCache()
30​
31 let result = getResult(mutationCache, options)
32​
33 const { subscribe } = readable(result, (set) => {
34 return mutationCache.subscribe(
35 notifyManager.batchCalls(() => {
36 const nextResult = replaceEqualDeep(
37 result,
38 getResult(mutationCache, options),
39 )
40 if (result !== nextResult) {
41 result = nextResult
42 set(result)
43 }
44 }),
45 )
46 })
47​
48 return { subscribe }