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