Open History to see the last commit
1import type { QueryClient, QueryKey, QueryObserver } from '@tanstack/query-core'
2import { notifyManager } from '@tanstack/query-core'
3import type { CreateBaseQueryOptions, CreateBaseQueryResult } from './types'
4import { useQueryClient } from './useQueryClient'
5import { derived, readable } from 'svelte/store'
6β
7export function createBaseQuery<
8 TQueryFnData,
9 TError,
10 TData,
11 TQueryData,
12 TQueryKey extends QueryKey,
13>(
14 options: CreateBaseQueryOptions<
15 TQueryFnData,
16 TError,
17 TData,
18 TQueryData,
19 TQueryKey
20 >,
21 Observer: typeof QueryObserver,
22 queryClient?: QueryClient,
23): CreateBaseQueryResult<TData, TError> {
24 const client = useQueryClient(queryClient)
25 const defaultedOptions = client.defaultQueryOptions(options)
26 defaultedOptions._optimisticResults = 'optimistic'
27β
28 let observer = new Observer<
29 TQueryFnData,
30 TError,
31 TData,
32 TQueryData,
33 TQueryKey
34 >(client, defaultedOptions)
35β
36 // Include callbacks in batch renders
37 if (defaultedOptions.onError) {
38 defaultedOptions.onError = notifyManager.batchCalls(
39 defaultedOptions.onError,
40 )
41 }
42β
43 if (defaultedOptions.onSuccess) {
44 defaultedOptions.onSuccess = notifyManager.batchCalls(
45 defaultedOptions.onSuccess,
46 )
47 }
48β
49 if (defaultedOptions.onSettled) {
50 defaultedOptions.onSettled = notifyManager.batchCalls(
51 defaultedOptions.onSettled,
52 )
53 }
54β
55 readable(observer).subscribe(($observer) => {
56 observer = $observer
57 // Do not notify on updates because of changes in the options because
58 // these changes should already be reflected in the optimistic result.
59 observer.setOptions(defaultedOptions, { listeners: false })
60 })
61β
62 const result = readable(observer.getCurrentResult(), (set) => {
63 return observer.subscribe(notifyManager.batchCalls(set))
64 })
65β
66 const { subscribe } = derived(result, ($result) => {
67 $result = observer.getOptimisticResult(defaultedOptions)
68 return !defaultedOptions.notifyOnChangeProps
69 ? observer.trackResult($result)
70 : $result
71 })
72β
73 return { subscribe }
74}