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

createMutation.svelte.ts

90 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 ...args
51 ) => {
52 observer.mutate(args[0] as TVariables, args[1]).catch(noop)
53 }
54​
55 let result = $state(observer.getCurrentResult())
56 watchChanges(
57 () => observer,
58 'pre',
59 () => {
60 result = observer.getCurrentResult()
61 },
62 )
63​
64 $effect.pre(() => {
65 const unsubscribe = observer.subscribe((val) => {
66 notifyManager.batchCalls(() => {
67 Object.assign(result, val)
68 })()
69 })
70 return unsubscribe
71 })
72​
73 const resultProxy = $derived(
74 new Proxy(result, {
75 get: (_, prop) => {
76 const r = {
77 ...result,
78 mutate,
79 mutateAsync: result.mutate,
80 }
81 if (prop == 'value') return r
82 // @ts-expect-error
83 return r[prop]
84 },
85 }),
86 )
87​
88 // @ts-expect-error
89 return resultProxy