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