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

createBaseQuery.svelte.ts

129 lines4.1 KB

1import { onDestroy } from 'svelte'
2import { useIsRestoring } from './useIsRestoring.js'
3import { useQueryClient } from './useQueryClient.js'
4import { createRawRef } from './containers.svelte.js'
5import { watchChanges } from './utils.svelte.js'
6import type { QueryClient, QueryKey, QueryObserver } from '@tanstack/query-core'
7import type {
8 Accessor,
9 CreateBaseQueryOptions,
10 CreateBaseQueryResult,
11} from './types.js'
12​
13/**
14 * Base implementation for `createQuery` and `createInfiniteQuery`
15 * @param options - A function that returns query options
16 * @param Observer - The observer from query-core
17 * @param queryClient - Custom query client which overrides provider
18 */
19export function createBaseQuery<
20 TQueryFnData,
21 TError,
22 TData,
23 TQueryData,
24 TQueryKey extends QueryKey,
25>(
26 options: Accessor<
27 CreateBaseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
28 >,
29 Observer: typeof QueryObserver,
30 queryClient?: Accessor<QueryClient>,
31): CreateBaseQueryResult<TData, TError> {
32 /** Load query client */
33 const client = $derived(useQueryClient(queryClient?.()))
34 const isRestoring = useIsRestoring()
35​
36 const resolvedOptions = $derived.by(() => {
37 const opts = client.defaultQueryOptions(options())
38 opts._optimisticResults = isRestoring.current ? 'isRestoring' : 'optimistic'
39 return opts
40 })
41​
42 /** Creates the observer */
43 // svelte-ignore state_referenced_locally - intentional, initial value
44 let observer = $state(
45 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
46 client,
47 resolvedOptions,
48 ),
49 )
50 watchChanges(
51 () => client,
52 'pre',
53 () => {
54 observer = new Observer<
55 TQueryFnData,
56 TError,
57 TData,
58 TQueryData,
59 TQueryKey
60 >(client, resolvedOptions)
61 },
62 )
63​
64 function createResult() {
65 const result = observer.getOptimisticResult(resolvedOptions)
66 return !resolvedOptions.notifyOnChangeProps
67 ? observer.trackResult(result)
68 : result
69 }
70 const [query, update] = createRawRef(
71 // svelte-ignore state_referenced_locally - intentional, initial value
72 createResult(),
73 )
74​
75 // The following is convoluted but necessary:
76 // Call eagerly so subscription happens on the server and on suspended branches in the client...
77 let unsubscribe =
78 isRestoring.current && typeof window !== 'undefined'
79 ? () => undefined
80 : observer.subscribe(() => update(createResult()))
81 // ...but also watch for state changes to resubscribe, and because Svelte right now doesn't
82 // run onDestroy on components with pending work that are destroyed again before they are resolved...
83 watchChanges(
84 () => [isRestoring.current, observer] as const,
85 'pre',
86 () => {
87 unsubscribe()
88 unsubscribe = isRestoring.current
89 ? () => undefined
90 : observer.subscribe(() => update(createResult()))
91 observer.updateResult()
92 return unsubscribe
93 },
94 )
95 // ...and finally also cleanup via onDestroy because that one runs on the server whereas $effect.pre does not.
96 // (in a try-catch because it theoretically can be called in a non-component context - that should not happen
97 // but it would be a breaking change technically to error out here. SSR-safe because this wouldn't be called during SSR if it was not in a component)
98 try {
99 onDestroy(() => {
100 unsubscribe()
101 })
102 } catch (e) {}
103​
104 watchChanges(
105 () => resolvedOptions,
106 'pre',
107 () => {
108 observer.setOptions(resolvedOptions)
109 },
110 )
111 watchChanges(
112 () => [resolvedOptions, observer],
113 'pre',
114 () => {
115 // The only reason this is necessary is because of `isRestoring`.
116 // Because we don't subscribe while restoring, the following can occur:
117 // - `isRestoring` is true
118 // - `isRestoring` becomes false
119 // - `observer.subscribe` and `observer.updateResult` is called in the above effect,
120 // but the subsequent `fetch` has already completed
121 // - `result` misses the intermediate restored-but-not-fetched state
122 //
123 // this could technically be its own effect but that doesn't seem necessary
124 update(createResult())
125 },
126 )
127​
128 return query