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

createBaseQuery.svelte.ts

135 lines4.3 KB

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