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