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

createBaseQuery.ts

74 lines2.0 KB

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 }