Open History to see the last commit
1import { QueryObserver } from '@tanstack/query-core'
2import { createBaseQuery } from './createBaseQuery.svelte.js'
3import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core'
4import type {
5 Accessor,
6 CreateQueryOptions,
7 CreateQueryResult,
8 DefinedCreateQueryResult,
9} from './types.js'
10import type {
11 DefinedInitialDataOptions,
12 UndefinedInitialDataOptions,
13} from './queryOptions.js'
14β
15/**
16 * Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
17 * The query runs when the options call for it β `enabled: false` skips the initial fetch.
18 *
19 * This overload is selected when `initialData` is set, so the resulting `data` is never `undefined` (unless
20 * a `select` changes `TData` to include `undefined`).
21 *
22 * @see {@link queryOptions} to share these options between `createQuery` and imperative APIs like `queryClient.query`.
23 * @param options - The {@link DefinedInitialDataOptions} to use β everything you can pass to `createQuery`,
24 * with `initialData` set, wrapped in an {@link Accessor} so options can be reactive.
25 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
26 * be used.
27 * @returns The current query result, typed so that `status` is `success` β or `error` if a fetch attempt
28 * fails while keeping the existing data (`status` never resolves to `pending` in this overload's type,
29 * since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived booleans for convenience.
30 *
31 * @example
32 * ```svelte
33 * <script lang="ts">
34 * import { createQuery } from '@tanstack/svelte-query'
35 *
36 * // `data` is `Post[]`, never `undefined`, thanks to `initialData` β even if a refetch fails,
37 * // so the list stays visible alongside the error.
38 * const query = createQuery(() => ({
39 * queryKey: ['posts'],
40 * queryFn: fetchPosts,
41 * initialData: [],
42 * }))
43 * </script>
44 *
45 * {#if query.isError}
46 * <span>Error: {query.error.message}</span>
47 * {/if}
48 * <ul>
49 * {#each query.data as post (post.id)}
50 * <li>{post.title}</li>
51 * {/each}
52 * </ul>
53 * ```
54 */
55export function createQuery<
56 TQueryFnData = unknown,
57 TError = DefaultError,
58 TData = TQueryFnData,
59 TQueryKey extends QueryKey = QueryKey,
60>(
61 options: Accessor<
62 DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>
63 >,
64 queryClient?: Accessor<QueryClient>,
65): DefinedCreateQueryResult<TData, TError>
66β
67/**
68 * Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
69 * The query runs when the options call for it β `enabled: false` skips the initial fetch.
70 *
71 * @see {@link queryOptions} to share these options between `createQuery` and imperative APIs like `queryClient.query`.
72 * @param options - The {@link UndefinedInitialDataOptions} to use β everything you can pass to `createQuery`,
73 * wrapped in an {@link Accessor} so options can be reactive.
74 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
75 * be used.
76 * @returns The current query result. `status` is `pending` if there is no cached data to display, `error` if
77 * the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
78 * are derived booleans for convenience.
79 *
80 * @example
81 * ```svelte
82 * <script lang="ts">
83 * import { createQuery } from '@tanstack/svelte-query'
84 *
85 * const query = createQuery(() => ({
86 * queryKey: ['posts'],
87 * queryFn: fetchPosts,
88 * }))
89 * </script>
90 *
91 * {#if query.status === 'pending'}
92 * Loading...
93 * {:else if query.status === 'error'}
94 * <span>Error: {query.error.message}</span>
95 * {:else}
96 * <ul>
97 * {#each query.data as post (post.id)}
98 * <li>{post.title}</li>
99 * {/each}
100 * </ul>
101 * {/if}
102 * ```
103 *
104 * @example
105 * The same query, checking `isPending`/`isError` instead of `status` β pick whichever reads better to you:
106 * ```svelte
107 * <script lang="ts">
108 * import { createQuery } from '@tanstack/svelte-query'
109 *
110 * const query = createQuery(() => ({
111 * queryKey: ['posts'],
112 * queryFn: fetchPosts,
113 * }))
114 * </script>
115 *
116 * {#if query.isPending}
117 * Loading...
118 * {:else if query.isError}
119 * <span>Error: {query.error.message}</span>
120 * {:else}
121 * <ul>
122 * {#each query.data as post (post.id)}
123 * <li>{post.title}</li>
124 * {/each}
125 * </ul>
126 * {/if}
127 * ```
128 */
129export function createQuery<
130 TQueryFnData = unknown,
131 TError = DefaultError,
132 TData = TQueryFnData,
133 TQueryKey extends QueryKey = QueryKey,
134>(
135 options: Accessor<
136 UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>
137 >,
138 queryClient?: Accessor<QueryClient>,
139): CreateQueryResult<TData, TError>
140β
141/**
142 * @see {@link queryOptions} to share these options between `createQuery` and imperative APIs like `queryClient.query`.
143 * @param options - The {@link CreateQueryOptions} to use β everything you can pass to `createQuery`, wrapped
144 * in an {@link Accessor} so options can be reactive.
145 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
146 * be used.
147 * @returns The current query result. `status` is `pending` if there is no cached data to display, `error` if
148 * the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
149 * are derived booleans for convenience.
150 *
151 * @example
152 * `select` derives whatever `data` a component needs from the cached value, without changing what's
153 * actually stored in the cache β the cache still holds the full `Post[]`, but `data` here is a `number`:
154 * ```svelte
155 * <script lang="ts">
156 * import { createQuery } from '@tanstack/svelte-query'
157 *
158 * const query = createQuery(() => ({
159 * queryKey: ['posts'],
160 * queryFn: fetchPosts,
161 * select: (posts) => posts.length,
162 * }))
163 * </script>
164 *
165 * {#if query.isPending}
166 * Loading...
167 * {:else if query.isError}
168 * <span>Error: {query.error.message}</span>
169 * {:else}
170 * <span>{query.data} posts</span>
171 * {/if}
172 * ```
173 *
174 * @example
175 * A dependent query, only enabled once `postId` is set β use `isLoading`, not `isPending`, so the
176 * loading state doesn't show while the query is disabled:
177 * ```svelte
178 * <script lang="ts">
179 * import { createQuery } from '@tanstack/svelte-query'
180 *
181 * let { postId }: { postId: number | undefined } = $props()
182 *
183 * const query = createQuery(() => ({
184 * queryKey: ['post', postId],
185 * queryFn: () => fetchPost(postId!),
186 * enabled: postId != null,
187 * }))
188 * </script>
189 *
190 * {#if postId == null}
191 * Select a post
192 * {:else if query.isLoading}
193 * Loading...
194 * {:else if query.isError}
195 * <span>Error: {query.error.message}</span>
196 * {:else}
197 * <h1>{query.data?.title}</h1>
198 * {/if}
199 * ```
200 *
201 * @example
202 * Seeding a detail query from an already-cached list, to skip the loading state:
203 * ```svelte
204 * <script lang="ts">
205 * import { createQuery, useQueryClient } from '@tanstack/svelte-query'
206 *
207 * let { postId }: { postId: number } = $props()
208 *
209 * const queryClient = useQueryClient()
210 *
211 * const query = createQuery(() => ({
212 * queryKey: ['post', postId],
213 * queryFn: () => fetchPost(postId),
214 * initialData: () =>
215 * queryClient
216 * .getQueryData<Array<Post>>(['posts'])
217 * ?.find((post) => post.id === postId),
218 * }))
219 * </script>
220 *
221 * {#if query.isError}
222 * <span>Error: {query.error.message}</span>
223 * {/if}
224 * <h1>{query.data?.title}</h1>
225 * ```
226 *
227 * @example
228 * Paginated data, keeping the previous page's data visible while the next page loads:
229 * ```svelte
230 * <script lang="ts">
231 * import { createQuery, keepPreviousData } from '@tanstack/svelte-query'
232 *
233 * let page = $state(0)
234 *
235 * const query = createQuery(() => ({
236 * queryKey: ['posts', page],
237 * queryFn: () => fetchPosts(page),
238 * placeholderData: keepPreviousData,
239 * }))
240 * </script>
241 *
242 * {#if query.isError}
243 * <span>Error: {query.error.message}</span>
244 * {/if}
245 * <ul>
246 * {#each query.data ?? [] as post (post.id)}
247 * <li>{post.title}</li>
248 * {/each}
249 * </ul>
250 * <button disabled={query.isPlaceholderData} onclick={() => page++}>
251 * Next Page
252 * </button>
253 * ```
254 */
255export function createQuery<
256 TQueryFnData,
257 TError = DefaultError,
258 TData = TQueryFnData,
259 TQueryKey extends QueryKey = QueryKey,
260>(
261 options: Accessor<CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>>,
262 queryClient?: Accessor<QueryClient>,
263): CreateQueryResult<TData, TError>
264β
265export function createQuery(
266 options: Accessor<CreateQueryOptions>,
267 queryClient?: Accessor<QueryClient>,
268) {
269 return createBaseQuery(options, QueryObserver, queryClient)
270}