( options: Accessor<CreateMutationOptions<TData, TError, TVariables, TContext>>, queryClient?: Accessor<QueryClient>, )
| 15 | * @param queryClient - Custom query client which overrides provider |
| 16 | */ |
| 17 | export 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( |
no test coverage detected