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

createMutation.svelte.ts

91 lines2.2 KB

1import { MutationObserver, noop, notifyManager } from '@tanstack/query-core'
2import { useQueryClient } from './useQueryClient.js'
3import { watchChanges } from './utils.svelte.js'
4import type {
5 Accessor,
6 CreateMutateFunction,
7 CreateMutationOptions,
8 CreateMutationResult,
9} from './types.js'
10​
11import type { DefaultError, QueryClient } from '@tanstack/query-core'
12​
13/**
14 * @param options - A function that returns mutation options
15 * @param queryClient - Custom query client which overrides provider
16 */
17export function createMutation<
18 TData = unknown,
19 TError = DefaultError,
20 TVariables = void,
21 TContext = unknown,
22>(
23 options: Accessor<CreateMutationOptions<TData, TError, TVariables, TContext>>,
24 queryClient?: Accessor<QueryClient>,
25): CreateMutationResult<TData, TError, TVariables, TContext> {
26 const client = $derived(useQueryClient(queryClient?.()))
27​
28 // svelte-ignore state_referenced_locally - intentional, initial value
29 let observer = $state(
30 // svelte-ignore state_referenced_locally - intentional, initial value
31 new MutationObserver<TData, TError, TVariables, TContext>(
32 client,
33 options(),
34 ),
35 )
36​
37 watchChanges(
38 () => client,
39 'pre',
40 () => {
41 observer = new MutationObserver(client, options())
42 },
43 )
44​
45 $effect.pre(() => {
46 observer.setOptions(options())
47 })
48​
49 const mutate = <CreateMutateFunction<TData, TError, TVariables, TContext>>((
50 variables,
51 mutateOptions,
52 ) => {
53 observer.mutate(variables, mutateOptions).catch(noop)
54 })
55​
56 let result = $state(observer.getCurrentResult())
57 watchChanges(
58 () => observer,
59 'pre',
60 () => {
61 result = observer.getCurrentResult()
62 },
63 )
64​
65 $effect.pre(() => {
66 const unsubscribe = observer.subscribe((val) => {
67 notifyManager.batchCalls(() => {
68 Object.assign(result, val)
69 })()
70 })
71 return unsubscribe
72 })
73​
74 const resultProxy = $derived(
75 new Proxy(result, {
76 get: (_, prop) => {
77 const r = {
78 ...result,
79 mutate,
80 mutateAsync: result.mutate,
81 }
82 if (prop == 'value') return r
83 // @ts-expect-error
84 return r[prop]
85 },
86 }),
87 )
88​
89 // @ts-expect-error
90 return resultProxy