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