snapshot of https://github.com/TanStack/query.git (main, 2026-09-16; blobs > 131072B omitted)
Some checks failed
autofix.ci / autofix (push) Failing after 4s
Release / Release (push) Has been skipped
GitHub Actions Security Analysis / Run zizmor (push) Failing after 2s

This commit is contained in:
upstream-mirror
2026-09-16 01:13:08 +05:00
commit 3a013ccdfe
3570 changed files with 490194 additions and 0 deletions

View File

@@ -0,0 +1,233 @@
---
id: createInfiniteQuery
title: createInfiniteQuery
---
## Call Signature
```ts
function createInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options, queryClient?): DefinedCreateInfiniteQueryResult<TData, TError>;
```
Defined in: [packages/svelte-query/src/createInfiniteQuery.ts:21](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/createInfiniteQuery.ts#L21)
### Type Parameters
#### TQueryFnData
`TQueryFnData` = `unknown`
#### TError
`TError` = `Error`
#### TData
`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
#### TPageParam
`TPageParam` = `unknown`
### Parameters
#### options
[`Accessor`](../type-aliases/Accessor.md)\<[`DefinedInitialDataInfiniteOptions`](../type-aliases/DefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>\>
#### queryClient?
[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
### Returns
[`DefinedCreateInfiniteQueryResult`](../type-aliases/DefinedCreateInfiniteQueryResult.md)\<`TData`, `TError`\>
## Call Signature
```ts
function createInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options, queryClient?): CreateInfiniteQueryResult<TData, TError>;
```
Defined in: [packages/svelte-query/src/createInfiniteQuery.ts:40](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/createInfiniteQuery.ts#L40)
### Type Parameters
#### TQueryFnData
`TQueryFnData` = `unknown`
#### TError
`TError` = `Error`
#### TData
`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
#### TPageParam
`TPageParam` = `unknown`
### Parameters
#### options
[`Accessor`](../type-aliases/Accessor.md)\<[`UndefinedInitialDataInfiniteOptions`](../type-aliases/UndefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>\>
#### queryClient?
[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
### Returns
[`CreateInfiniteQueryResult`](../type-aliases/CreateInfiniteQueryResult.md)\<`TData`, `TError`\>
## Call Signature
```ts
function createInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options, queryClient?): CreateInfiniteQueryResult<TData, TError>;
```
Defined in: [packages/svelte-query/src/createInfiniteQuery.ts:152](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/createInfiniteQuery.ts#L152)
### Type Parameters
#### TQueryFnData
`TQueryFnData`
#### TError
`TError` = `Error`
#### TData
`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
#### TPageParam
`TPageParam` = `unknown`
### Parameters
#### options
[`Accessor`](../type-aliases/Accessor.md)\<[`CreateInfiniteQueryOptions`](../type-aliases/CreateInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>\>
The [CreateInfiniteQueryOptions](../type-aliases/CreateInfiniteQueryOptions.md) to use — everything you can pass to
`createInfiniteQuery`, wrapped in an [Accessor](../type-aliases/Accessor.md) so options can be reactive.
#### queryClient?
[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
### Returns
[`CreateInfiniteQueryResult`](../type-aliases/CreateInfiniteQueryResult.md)\<`TData`, `TError`\>
The current query result, plus `fetchNextPage`/`fetchPreviousPage`/`hasNextPage`/`hasPreviousPage`
to page through the query.
### See
[infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `createInfiniteQuery` and imperative APIs
like `queryClient.infiniteQuery`.
### Examples
Fetching the next page from a "Load More" button click:
```svelte
<script lang="ts">
import { createInfiniteQuery } from '@tanstack/svelte-query'
const query = createInfiniteQuery(() => ({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
}))
</script>
{#if query.isPending}
Loading...
{:else if query.isError}
<span>Error: {query.error.message}</span>
{:else}
<ul>
{#each query.data.pages as page}
{#each page.projects as project (project.id)}
<li>{project.name}</li>
{/each}
{/each}
</ul>
<button
onclick={() => query.fetchNextPage()}
disabled={!query.hasNextPage || query.isFetching}
>
{query.isFetchingNextPage
? 'Loading more...'
: query.hasNextPage
? 'Load More'
: 'Nothing more to load'}
</button>
{/if}
```
Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
sentinel element after the list:
```svelte
<script lang="ts">
import { createInfiniteQuery } from '@tanstack/svelte-query'
const query = createInfiniteQuery(() => ({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
}))
let sentinel: HTMLDivElement | undefined = $state()
$effect(() => {
if (sentinel == null || !query.hasNextPage || query.isFetching) return
const observer = new IntersectionObserver(([entry]) => {
if (entry?.isIntersecting) query.fetchNextPage()
})
observer.observe(sentinel)
return () => observer.disconnect()
})
</script>
{#if query.isPending}
Loading...
{:else if query.isError}
<span>Error: {query.error.message}</span>
{:else}
<ul>
{#each query.data.pages as page}
{#each page.projects as project (project.id)}
<li>{project.name}</li>
{/each}
{/each}
</ul>
<div bind:this={sentinel}></div>
{/if}
```

View File

@@ -0,0 +1,201 @@
---
id: createMutation
title: createMutation
---
```ts
function createMutation<TData, TError, TVariables, TContext>(options, queryClient?): CreateMutationResult<TData, TError, TVariables, TContext>;
```
Defined in: [packages/svelte-query/src/createMutation.svelte.ts:171](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/createMutation.svelte.ts#L171)
Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
`createMutation` is the function for that.
## Type Parameters
### TData
`TData` = `unknown`
### TError
`TError` = `Error`
### TVariables
`TVariables` = `void`
### TContext
`TContext` = `unknown`
## Parameters
### options
[`Accessor`](../type-aliases/Accessor.md)\<[`CreateMutationOptions`](../type-aliases/CreateMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TContext`\>\>
The [CreateMutationOptions](../type-aliases/CreateMutationOptions.md) to use, wrapped in an [Accessor](../type-aliases/Accessor.md) so options can be
reactive.
### queryClient?
[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
## Returns
[`CreateMutationResult`](../type-aliases/CreateMutationResult.md)\<`TData`, `TError`, `TVariables`, `TContext`\>
`mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
mutation definition. If you make multiple requests, `onSuccess` will fire only after the latest call you've
made.
## See
[mutationOptions](mutationOptions.md) to share these options across multiple `createMutation` call sites, or to look
the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).
## Examples
```svelte
<script lang="ts">
import { createMutation, useQueryClient } from '@tanstack/svelte-query'
const queryClient = useQueryClient()
const addMutation = createMutation(() => ({
mutationFn: addTodo,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
}))
</script>
<button
onclick={() =>
addMutation.mutate('Item', {
onError: (error) => console.error('Failed to add item:', error),
})
}
>
Add
</button>
```
Rendering the mutation's own state, rather than just firing it off:
```svelte
<script lang="ts">
import { createMutation, useQueryClient } from '@tanstack/svelte-query'
const queryClient = useQueryClient()
const addMutation = createMutation(() => ({
mutationFn: addTodo,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
}))
</script>
{#if addMutation.isPending}
Adding todo...
{:else}
{#if addMutation.isError}
<div>An error occurred: {addMutation.error.message}</div>
{/if}
<button onclick={() => addMutation.mutate('Item')}>Add</button>
{/if}
```
Optimistic update via `onMutate`, rolling back on `onError`:
```svelte
<script lang="ts">
import { createMutation, useQueryClient } from '@tanstack/svelte-query'
const queryClient = useQueryClient()
const addMutation = createMutation(() => ({
mutationFn: addTodo,
onMutate: async (newTodo: string) => {
await queryClient.cancelQueries({ queryKey: ['todos'] })
const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
queryClient.setQueryData<Array<string>>(['todos'], (old) => [
...(old ?? []),
newTodo,
])
// Passed to `onError` as `onMutateResult` if the mutation fails.
return { previousTodos }
},
onError: (_err, _newTodo, onMutateResult) => {
queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] })
},
}))
</script>
<button onclick={() => addMutation.mutate('Item')}>Add</button>
```
Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a
promise per call instead, so you can wait for all of them when they succeed:
```svelte
<script lang="ts">
import { createMutation, useQueryClient } from '@tanstack/svelte-query'
const queryClient = useQueryClient()
const addMutation = createMutation(() => ({
mutationFn: addTodo,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
}))
async function handleAddAll(todos: Array<string>) {
try {
await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
} catch (error) {
console.error('Failed to add todos:', error)
}
}
</script>
<button onclick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
Add all
</button>
```
If some of the mutations above can fail independently of the others, and you want to know which ones
did — rather than losing that information the moment the first one rejects — swap `Promise.all` for
`Promise.allSettled`:
```svelte
<script lang="ts">
import { createMutation, useQueryClient } from '@tanstack/svelte-query'
const queryClient = useQueryClient()
const addMutation = createMutation(() => ({
mutationFn: addTodo,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
}))
async function handleAddAll(todos: Array<string>) {
const addResults = await Promise.allSettled(
todos.map((todo) => addMutation.mutateAsync(todo)),
)
addResults.forEach((addResult, index) => {
if (addResult.status === 'rejected') {
console.error(`Failed to add "${todos[index]}":`, addResult.reason)
}
})
}
</script>
<button onclick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
Add all
</button>
```

View File

@@ -0,0 +1,110 @@
---
id: createQueries
title: createQueries
---
```ts
function createQueries<T, TCombinedResult>(createQueriesOptions, queryClient?): TCombinedResult;
```
Defined in: [packages/svelte-query/src/createQueries.svelte.ts:260](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/createQueries.svelte.ts#L260)
## Type Parameters
### T
`T` *extends* `any`[]
### TCombinedResult
`TCombinedResult` = `T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetCreateQueryResult`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetCreateQueryResult`\<`Head`\>, `GetCreateQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetCreateQueryResult`\<`Head`\>, `GetCreateQueryResult`\<`Head`\>, `GetCreateQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : \[`...{ [K in (...)]: (...) }[]`\] : \[...\{ \[K in string \| number \| symbol\]: GetCreateQueryResult\<Tails\[K\<(...)\>\]\> \}\[\]\] : \{ \[K in string \| number \| symbol\]: GetCreateQueryResult\<T\[K\<K\>\]\> \}
## Parameters
### createQueriesOptions
[`Accessor`](../type-aliases/Accessor.md)\<\{
`combine?`: (`result`) => `TCombinedResult`;
`queries`: \| readonly \[`T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetCreateQueryOptionsForCreateQueries`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetCreateQueryOptionsForCreateQueries`\<...\>, `GetCreateQueryOptionsForCreateQueries`\<...\>\] : \[`...(...)[]`\] *extends* \[..., `...(...)[]`\] ? ... *extends* ... ? ... : ... : ... *extends* ... ? ... : ... : readonly `unknown`[] *extends* `T` ? `T` : `T` *extends* `CreateQueryOptionsForCreateQueries`\<..., ..., ..., ...\>[] ? `CreateQueryOptionsForCreateQueries`\<..., ..., ..., ...\>[] : `CreateQueryOptionsForCreateQueries`\<..., ..., ..., ...\>[]\]
\| readonly \[\{ \[K in string \| number \| symbol\]: GetCreateQueryOptionsForCreateQueries\<T\[K\<K\>\]\> \}\];
\}\>
The `queries` array to run, and an optional `combine` function, wrapped in an
[Accessor](../type-aliases/Accessor.md) so options can be reactive.
### queryClient?
[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context
will be used.
## Returns
`TCombinedResult`
An array with one result per query, in the same order as `queries` — or, if `combine` is provided,
whatever `combine` returns.
## Examples
```svelte
<script lang="ts">
import { createQueries } from '@tanstack/svelte-query'
let { ids }: { ids: Array<number> } = $props()
const postQueries = createQueries(() => ({
queries: ids.map((id) => ({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
staleTime: Infinity,
})),
}))
</script>
<ul>
{#each postQueries as query, index (ids[index])}
{#if query.isPending}
<li>Loading...</li>
{:else if query.isError}
<li>Error: {query.error.message}</li>
{:else}
<li>{query.data.title}</li>
{/if}
{/each}
</ul>
```
Combining results into a single value:
```svelte
<script lang="ts">
import { createQueries } from '@tanstack/svelte-query'
let { ids }: { ids: Array<number> } = $props()
const combined = createQueries(() => ({
queries: ids.map((id) => ({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
})),
combine: (postQueries) => ({
data: postQueries.map((query) => query.data),
isPending: postQueries.some((query) => query.isPending),
isError: postQueries.some((query) => query.isError),
}),
}))
</script>
{#if combined.isPending}
Loading...
{:else if combined.isError}
Error loading posts
{:else}
<ul>
{#each combined.data as post}
<li>{post?.title}</li>
{/each}
</ul>
{/if}
```

View File

@@ -0,0 +1,344 @@
---
id: createQuery
title: createQuery
---
## Call Signature
```ts
function createQuery<TQueryFnData, TError, TData, TQueryKey>(options, queryClient?): CreateQueryResult<TData, TError>;
```
Defined in: [packages/svelte-query/src/createQuery.ts:74](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/createQuery.ts#L74)
### Type Parameters
#### TQueryFnData
`TQueryFnData` = `unknown`
#### TError
`TError` = `Error`
#### TData
`TData` = `TQueryFnData`
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
### Parameters
#### options
[`Accessor`](../type-aliases/Accessor.md)\<[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>\>
The [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use — everything you can pass to `createQuery`,
wrapped in an [Accessor](../type-aliases/Accessor.md) so options can be reactive.
#### queryClient?
[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
### Returns
[`CreateQueryResult`](../type-aliases/CreateQueryResult.md)\<`TData`, `TError`\>
The current query result. `status` is `pending` if there is no cached data to display, `error` if
the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
are derived booleans for convenience.
### See
[queryOptions](queryOptions.md) to share these options between `createQuery` and imperative APIs like `queryClient.query`.
### Examples
```svelte
<script lang="ts">
import { createQuery } from '@tanstack/svelte-query'
const query = createQuery(() => ({
queryKey: ['posts'],
queryFn: fetchPosts,
}))
</script>
{#if query.status === 'pending'}
Loading...
{:else if query.status === 'error'}
<span>Error: {query.error.message}</span>
{:else}
<ul>
{#each query.data as post (post.id)}
<li>{post.title}</li>
{/each}
</ul>
{/if}
```
The same query, checking `isPending`/`isError` instead of `status` — pick whichever reads better to you:
```svelte
<script lang="ts">
import { createQuery } from '@tanstack/svelte-query'
const query = createQuery(() => ({
queryKey: ['posts'],
queryFn: fetchPosts,
}))
</script>
{#if query.isPending}
Loading...
{:else if query.isError}
<span>Error: {query.error.message}</span>
{:else}
<ul>
{#each query.data as post (post.id)}
<li>{post.title}</li>
{/each}
</ul>
{/if}
```
## Call Signature
```ts
function createQuery<TQueryFnData, TError, TData, TQueryKey>(options, queryClient?): DefinedCreateQueryResult<TData, TError>;
```
Defined in: [packages/svelte-query/src/createQuery.ts:122](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/createQuery.ts#L122)
This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`.
### Type Parameters
#### TQueryFnData
`TQueryFnData` = `unknown`
#### TError
`TError` = `Error`
#### TData
`TData` = `TQueryFnData`
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
### Parameters
#### options
[`Accessor`](../type-aliases/Accessor.md)\<[`DefinedInitialDataOptions`](../type-aliases/DefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>\>
The [DefinedInitialDataOptions](../type-aliases/DefinedInitialDataOptions.md) to use — everything you can pass to `createQuery`,
with `initialData` set, wrapped in an [Accessor](../type-aliases/Accessor.md) so options can be reactive.
#### queryClient?
[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
### Returns
[`DefinedCreateQueryResult`](../type-aliases/DefinedCreateQueryResult.md)\<`TData`, `TError`\>
The current query result, typed so that `status` is `success` — or `error` if a fetch attempt
fails while keeping the existing data (`status` never resolves to `pending` in this overload's type,
since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived booleans for convenience.
### See
[queryOptions](queryOptions.md) to share these options between `createQuery` and imperative APIs like `queryClient.query`.
### Example
```svelte
<script lang="ts">
import { createQuery } from '@tanstack/svelte-query'
// `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails,
// so the list stays visible alongside the error.
const query = createQuery(() => ({
queryKey: ['posts'],
queryFn: fetchPosts,
initialData: [],
}))
</script>
{#if query.isError}
<span>Error: {query.error.message}</span>
{/if}
<ul>
{#each query.data as post (post.id)}
<li>{post.title}</li>
{/each}
</ul>
```
## Call Signature
```ts
function createQuery<TQueryFnData, TError, TData, TQueryKey>(options, queryClient?): CreateQueryResult<TData, TError>;
```
Defined in: [packages/svelte-query/src/createQuery.ts:248](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/createQuery.ts#L248)
### Type Parameters
#### TQueryFnData
`TQueryFnData`
#### TError
`TError` = `Error`
#### TData
`TData` = `TQueryFnData`
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
### Parameters
#### options
[`Accessor`](../type-aliases/Accessor.md)\<[`CreateQueryOptions`](../type-aliases/CreateQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>\>
The [CreateQueryOptions](../type-aliases/CreateQueryOptions.md) to use — everything you can pass to `createQuery`, wrapped
in an [Accessor](../type-aliases/Accessor.md) so options can be reactive.
#### queryClient?
[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
### Returns
[`CreateQueryResult`](../type-aliases/CreateQueryResult.md)\<`TData`, `TError`\>
The current query result. `status` is `pending` if there is no cached data to display, `error` if
the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
are derived booleans for convenience.
### See
[queryOptions](queryOptions.md) to share these options between `createQuery` and imperative APIs like `queryClient.query`.
### Examples
`select` derives whatever `data` a component needs from the cached value, without changing what's
actually stored in the cache — the cache still holds the full `Post[]`, but `data` here is a `number`:
```svelte
<script lang="ts">
import { createQuery } from '@tanstack/svelte-query'
const query = createQuery(() => ({
queryKey: ['posts'],
queryFn: fetchPosts,
select: (posts) => posts.length,
}))
</script>
{#if query.isPending}
Loading...
{:else if query.isError}
<span>Error: {query.error.message}</span>
{:else}
<span>{query.data} posts</span>
{/if}
```
A dependent query, only enabled once `postId` is set — use `isLoading`, not `isPending`, so the
loading state doesn't show while the query is disabled:
```svelte
<script lang="ts">
import { createQuery } from '@tanstack/svelte-query'
let { postId }: { postId: number | undefined } = $props()
const query = createQuery(() => ({
queryKey: ['post', postId],
queryFn: () => fetchPost(postId!),
enabled: postId != null,
}))
</script>
{#if postId == null}
Select a post
{:else if query.isLoading}
Loading...
{:else if query.isError}
<span>Error: {query.error.message}</span>
{:else}
<h1>{query.data?.title}</h1>
{/if}
```
Seeding a detail query from an already-cached list, to skip the loading state:
```svelte
<script lang="ts">
import { createQuery, useQueryClient } from '@tanstack/svelte-query'
let { postId }: { postId: number } = $props()
const queryClient = useQueryClient()
const query = createQuery(() => ({
queryKey: ['post', postId],
queryFn: () => fetchPost(postId),
initialData: () =>
queryClient
.getQueryData<Array<Post>>(['posts'])
?.find((post) => post.id === postId),
}))
</script>
{#if query.isError}
<span>Error: {query.error.message}</span>
{/if}
<h1>{query.data?.title}</h1>
```
Paginated data, keeping the previous page's data visible while the next page loads:
```svelte
<script lang="ts">
import { createQuery, keepPreviousData } from '@tanstack/svelte-query'
let page = $state(0)
const query = createQuery(() => ({
queryKey: ['posts', page],
queryFn: () => fetchPosts(page),
placeholderData: keepPreviousData,
}))
</script>
{#if query.isError}
<span>Error: {query.error.message}</span>
{/if}
<ul>
{#each query.data ?? [] as post (post.id)}
<li>{post.title}</li>
{/each}
</ul>
<button disabled={query.isPlaceholderData} onclick={() => page++}>
Next Page
</button>
```

View File

@@ -0,0 +1,23 @@
---
id: defaultShouldDehydrateMutation
title: defaultShouldDehydrateMutation
---
```ts
function defaultShouldDehydrateMutation(mutation): boolean;
```
Defined in: [packages/query-core/src/hydration.ts:177](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L177)
The default `shouldDehydrateMutation` predicate used by `dehydrate`. Only dehydrates mutations that are
currently paused (e.g. paused by `networkMode` while offline).
## Parameters
### mutation
[`Mutation`](../classes/Mutation.md)
## Returns
`boolean`

View File

@@ -0,0 +1,23 @@
---
id: defaultShouldDehydrateQuery
title: defaultShouldDehydrateQuery
---
```ts
function defaultShouldDehydrateQuery(query): boolean;
```
Defined in: [packages/query-core/src/hydration.ts:185](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L185)
The default `shouldDehydrateQuery` predicate used by `dehydrate`. Only dehydrates queries whose status is
`'success'`.
## Parameters
### query
[`Query`](../classes/Query.md)
## Returns
`boolean`

View File

@@ -0,0 +1,43 @@
---
id: dehydrate
title: dehydrate
---
```ts
function dehydrate(client, options): DehydratedState;
```
Defined in: [packages/query-core/src/hydration.ts:207](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L207)
Dehydrates a `QueryClient`'s cache (queries and mutations) into a plain, serializable `DehydratedState`,
typically to embed in server-rendered markup and later restore into a client-side `QueryClient` via `hydrate`.
Which queries/mutations are included, and how their data/errors are transformed, is controlled by `options`,
falling back to the client's `dehydrate` default options, and finally to `defaultShouldDehydrateQuery` /
`defaultShouldDehydrateMutation`.
## Parameters
### client
[`QueryClient`](../classes/QueryClient.md)
### options
[`DehydrateOptions`](../interfaces/DehydrateOptions.md) = `{}`
## Returns
[`DehydratedState`](../interfaces/DehydratedState.md)
## Example
```ts
const queryClient = new QueryClient()
await queryClient.prefetchQuery({
queryKey: ['posts'],
queryFn: getPosts,
})
const dehydratedState = dehydrate(queryClient)
```

View File

@@ -0,0 +1,43 @@
---
id: dehydrateQuery
title: dehydrateQuery
---
```ts
function dehydrateQuery(
query,
serializeData?,
shouldRedactErrors?): DehydratedQuery;
```
Defined in: [packages/query-core/src/hydration.ts:148](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L148)
Dehydrates a single `Query` into a serializable `DehydratedQuery` snapshot. Note that most query config (e.g.
`queryFn`, `staleTime`) is not dehydrated but instead meant to be configured again when consuming the
de/rehydrated data, typically with `useQuery` on the client. If the query is still `pending`, its in-flight
promise is dehydrated too so it can be resumed on the other side instead of re-fetched.
## Parameters
### query
[`Query`](../classes/Query.md)
The query to dehydrate.
### serializeData?
`TransformerFn`
Optional transform applied to `query.state.data` before it is included in the snapshot.
### shouldRedactErrors?
(`error`) => `boolean`
Optional predicate; if it returns `false` for the promise's rejection error, that
error is kept as-is instead of being redacted.
## Returns
`DehydratedQuery`

View File

@@ -0,0 +1,52 @@
---
id: experimental_streamedQuery
title: experimental_streamedQuery
---
```ts
function experimental_streamedQuery<TQueryFnData, TData, TQueryKey>(streamFn): QueryFunction<TData, TQueryKey>;
```
Defined in: [packages/query-core/src/streamedQuery.ts:75](https://github.com/TanStack/query/blob/main/packages/query-core/src/streamedQuery.ts#L75)
This is a helper function to create a query function that streams data from an AsyncIterable.
Data will be an Array of all the chunks received.
The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
The query will stay in fetchStatus 'fetching' until the stream ends.
## Type Parameters
### TQueryFnData
`TQueryFnData` = `unknown`
### TData
`TData` = `TQueryFnData`[]
### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
## Parameters
### streamFn
`StreamedQueryParams`\<`TQueryFnData`, `TData`, `TQueryKey`\>
The function that returns an AsyncIterable to stream data from.
## Returns
[`QueryFunction`](../type-aliases/QueryFunction.md)\<`TData`, `TQueryKey`\>
## Example
```ts
await queryClient.query({
queryKey: ['data'],
queryFn: streamedQuery({
streamFn: fetchDataInChunks,
}),
})
```

View File

@@ -0,0 +1,16 @@
---
id: getIsRestoringContext
title: getIsRestoringContext
---
```ts
function getIsRestoringContext(): Box<boolean>;
```
Defined in: [packages/svelte-query/src/context.ts:52](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/context.ts#L52)
Retrieves a `isRestoring` from Svelte's context
## Returns
`Box`\<`boolean`\>

View File

@@ -0,0 +1,23 @@
---
id: getQueryClientContext
title: getQueryClientContext
---
```ts
function getQueryClientContext(): QueryClient;
```
Defined in: [packages/svelte-query/src/context.ts:14](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/context.ts#L14)
Retrieves the `QueryClient` set on Svelte's context by `QueryClientProvider` (or by
[setQueryClientContext](setQueryClientContext.md) directly). This is what [useQueryClient](useQueryClient.md) calls internally.
## Returns
[`QueryClient`](../classes/QueryClient.md)
The `QueryClient` set on context, whether by `QueryClientProvider` or [setQueryClientContext](setQueryClientContext.md).
## Throws
If no `QueryClient` was found in context.

View File

@@ -0,0 +1,30 @@
---
id: hashKey
title: hashKey
---
```ts
function hashKey(queryKey): string;
```
Defined in: [packages/query-core/src/utils.ts:284](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L284)
Default query & mutation keys hash function.
Hashes the value into a stable hash.
## Parameters
### queryKey
readonly `unknown`[]
## Returns
`string`
## Example
```ts
// Object keys are sorted, so key order doesn't affect the hash:
hashKey(['todos', { page: 1, filter: 'done' }]) // === '["todos",{"filter":"done","page":1}]'
```

View File

@@ -0,0 +1,49 @@
---
id: hydrate
title: hydrate
---
```ts
function hydrate(
client,
dehydratedState,
options?): void;
```
Defined in: [packages/query-core/src/hydration.ts:264](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L264)
Restores a `DehydratedState` (as produced by `dehydrate`) into a `QueryClient`'s cache, typically to seed the
client with data already fetched on the server. `mutations` and `queries` are each optional on `dehydratedState`.
Queries not yet in the cache are built from the dehydrated snapshot; queries that already exist are only updated
when the dehydrated data is newer than what's already cached. Newly built queries have their `fetchStatus` reset
to `'idle'` so they don't hydrate stuck in a fetching state. If a dehydrated query still had an in-flight
promise, it is resumed via `query.fetch()` (reusing that promise as `initialPromise`) rather than re-invoking
`queryFn`.
## Parameters
### client
[`QueryClient`](../classes/QueryClient.md)
### dehydratedState
`Partial`\<[`DehydratedState`](../interfaces/DehydratedState.md)\>
### options?
[`HydrateOptions`](../interfaces/HydrateOptions.md)
## Returns
`void`
## Example
```ts
// dehydratedState was produced by `dehydrate` on the server
// and sent to the client, e.g. embedded in server-rendered markup.
const queryClient = new QueryClient()
hydrate(queryClient, dehydratedState)
```

View File

@@ -0,0 +1,178 @@
---
id: infiniteQueryOptions
title: infiniteQueryOptions
---
## Call Signature
```ts
function infiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options): CreateInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & object & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData, unknown>, TError>;
```
Defined in: [packages/svelte-query/src/infiniteQueryOptions.ts:92](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/infiniteQueryOptions.ts#L92)
You can generally pass everything to `infiniteQueryOptions` that you can also pass to `createInfiniteQuery`.
These options can be shared across `createInfiniteQuery` calls and imperative APIs such as
`queryClient.infiniteQuery`. `options.queryKey` is required and is the query key to generate options for.
This overload is selected when `initialData` is set.
### Type Parameters
#### TQueryFnData
`TQueryFnData`
#### TError
`TError` = `Error`
#### TData
`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
#### TPageParam
`TPageParam` = `unknown`
### Parameters
#### options
[`DefinedInitialDataInfiniteOptions`](../type-aliases/DefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
The [DefinedInitialDataInfiniteOptions](../type-aliases/DefinedInitialDataInfiniteOptions.md) to use — everything you can pass to
`createInfiniteQuery`, with `initialData` set.
### Returns
[`CreateInfiniteQueryOptions`](../type-aliases/CreateInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> & `object` & [`QueryKeyWithDataTag`](../type-aliases/QueryKeyWithDataTag.md)\<`TQueryKey`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>, `TError`\>
The same options object, typed so that `queryKey` carries the inferred data type.
### See
[createInfiniteQuery](createInfiniteQuery.md) to run an infinite query with these options.
### Example
`initialData` skips the loading state on first render — even if a refetch fails, the list stays
visible alongside the error:
```svelte
<script lang="ts">
import { infiniteQueryOptions, createInfiniteQuery } from '@tanstack/svelte-query'
const projectsOptions = infiniteQueryOptions({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
initialData: { pages: [], pageParams: [] },
})
const query = createInfiniteQuery(() => projectsOptions)
</script>
{#if query.isError}
<span>Error: {query.error.message}</span>
{/if}
<ul>
{#each query.data.pages as page}
{#each page.projects as project (project.id)}
<li>{project.name}</li>
{/each}
{/each}
</ul>
```
## Call Signature
```ts
function infiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options): CreateInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & object & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData, unknown>, TError>;
```
Defined in: [packages/svelte-query/src/infiniteQueryOptions.ts:159](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/infiniteQueryOptions.ts#L159)
You can generally pass everything to `infiniteQueryOptions` that you can also pass to `createInfiniteQuery`.
These options can be shared across `createInfiniteQuery` calls and imperative APIs such as
`queryClient.infiniteQuery`. `options.queryKey` is required and is the query key to generate options for.
### Type Parameters
#### TQueryFnData
`TQueryFnData`
#### TError
`TError` = `Error`
#### TData
`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
#### TPageParam
`TPageParam` = `unknown`
### Parameters
#### options
[`UndefinedInitialDataInfiniteOptions`](../type-aliases/UndefinedInitialDataInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
The [UndefinedInitialDataInfiniteOptions](../type-aliases/UndefinedInitialDataInfiniteOptions.md) to use — everything you can pass to
`createInfiniteQuery`.
### Returns
[`CreateInfiniteQueryOptions`](../type-aliases/CreateInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\> & `object` & [`QueryKeyWithDataTag`](../type-aliases/QueryKeyWithDataTag.md)\<`TQueryKey`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `unknown`\>, `TError`\>
The same options object, typed so that `queryKey` carries the inferred data type.
### See
[createInfiniteQuery](createInfiniteQuery.md) to run an infinite query with these options.
### Example
A parameterized factory, so the same options object can be reused per `postId`:
```svelte
<script lang="ts">
import { infiniteQueryOptions, createInfiniteQuery } from '@tanstack/svelte-query'
let { postId }: { postId: string } = $props()
const commentsOptions = (postId: string) =>
infiniteQueryOptions({
queryKey: ['post', postId, 'comments'],
queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
})
const query = createInfiniteQuery(() => commentsOptions(postId))
</script>
{#if query.isPending}
Loading...
{:else if query.isError}
<span>Error: {query.error.message}</span>
{:else}
<ul>
{#each query.data.pages as page}
{#each page.comments as comment (comment.id)}
<li>{comment.text}</li>
{/each}
{/each}
</ul>
{/if}
```

View File

@@ -0,0 +1,24 @@
---
id: isCancelledError
title: isCancelledError
---
```ts
function isCancelledError(value): value is CancelledError;
```
Defined in: [packages/query-core/src/retryer.ts:90](https://github.com/TanStack/query/blob/main/packages/query-core/src/retryer.ts#L90)
## Parameters
### value
`any`
## Returns
`value is CancelledError`
## Deprecated
Use instanceof `CancelledError` instead.

View File

@@ -0,0 +1,40 @@
---
id: keepPreviousData
title: keepPreviousData
---
```ts
function keepPreviousData<T>(previousData): T | undefined;
```
Defined in: [packages/query-core/src/utils.ts:493](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L493)
Intended to be passed as a query's `placeholderData` option, for example
`placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new
query key is fetching, it keeps displaying the previously fetched data until the new data arrives.
## Type Parameters
### T
`T`
## Parameters
### previousData
`T` | `undefined`
## Returns
`T` \| `undefined`
## Example
```ts
new QueryObserver(queryClient, {
queryKey: ['posts', page],
queryFn: () => fetchPosts(page),
placeholderData: keepPreviousData,
})
```

View File

@@ -0,0 +1,38 @@
---
id: matchMutation
title: matchMutation
---
```ts
function matchMutation(filters, mutation): boolean;
```
Defined in: [packages/query-core/src/utils.ts:237](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L237)
Checks whether a mutation matches the given [MutationFilters](../interfaces/MutationFilters.md).
Every filter that is specified must match; filters that are left unspecified are ignored.
If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match.
## Parameters
### filters
[`MutationFilters`](../interfaces/MutationFilters.md)
### mutation
[`Mutation`](../classes/Mutation.md)\<`any`, `any`\>
## Returns
`boolean`
## Example
```ts
const mutationCache = queryClient.getMutationCache()
const matchingMutations = mutationCache
.getAll()
.filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation))
```

View File

@@ -0,0 +1,37 @@
---
id: matchQuery
title: matchQuery
---
```ts
function matchQuery(filters, query): boolean;
```
Defined in: [packages/query-core/src/utils.ts:175](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L175)
Checks whether a query matches the given [QueryFilters](../interfaces/QueryFilters.md).
Every filter that is specified must match; filters that are left unspecified are ignored.
## Parameters
### filters
[`QueryFilters`](../interfaces/QueryFilters.md)
### query
[`Query`](../classes/Query.md)\<`any`, `any`, `any`, `any`\>
## Returns
`boolean`
## Example
```ts
const queryCache = queryClient.getQueryCache()
const matchingQueries = queryCache
.getAll()
.filter((query) => matchQuery({ queryKey: ['posts'] }, query))
```

View File

@@ -0,0 +1,136 @@
---
id: mutationOptions
title: mutationOptions
---
## Call Signature
```ts
function mutationOptions<TData, TError, TVariables, TOnMutateResult>(options): WithRequired<CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>, "mutationKey">;
```
Defined in: [packages/svelte-query/src/mutationOptions.ts:34](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/mutationOptions.ts#L34)
You can generally pass everything to `mutationOptions` that you can also pass to `createMutation`. This
overload requires `mutationKey`, so the resulting options can be looked up elsewhere (e.g. with
`useMutationState`).
### Type Parameters
#### TData
`TData` = `unknown`
#### TError
`TError` = `Error`
#### TVariables
`TVariables` = `void`
#### TOnMutateResult
`TOnMutateResult` = `unknown`
### Parameters
#### options
[`WithRequired`](../type-aliases/WithRequired.md)\<[`CreateMutationOptions`](../type-aliases/CreateMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
The options to use — everything you can pass to `createMutation`, with `mutationKey` set.
### Returns
[`WithRequired`](../type-aliases/WithRequired.md)\<[`CreateMutationOptions`](../type-aliases/CreateMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
The same options object.
### See
[createMutation](createMutation.md) to run a mutation with these options.
### Example
Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator:
```svelte
<script lang="ts">
import { mutationOptions, useMutationState } from '@tanstack/svelte-query'
const createPostOptions = mutationOptions({
mutationKey: ['posts', 'create'],
mutationFn: createPost,
})
const pending = useMutationState({
filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' },
})
</script>
{#if pending.length > 0}
<span>Saving…</span>
{/if}
```
## Call Signature
```ts
function mutationOptions<TData, TError, TVariables, TOnMutateResult>(options): Omit<CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>, "mutationKey">;
```
Defined in: [packages/svelte-query/src/mutationOptions.ts:71](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/mutationOptions.ts#L71)
You can generally pass everything to `mutationOptions` that you can also pass to `createMutation`.
### Type Parameters
#### TData
`TData` = `unknown`
#### TError
`TError` = `Error`
#### TVariables
`TVariables` = `void`
#### TOnMutateResult
`TOnMutateResult` = `unknown`
### Parameters
#### options
`Omit`\<[`CreateMutationOptions`](../type-aliases/CreateMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
The options to use — everything you can pass to `createMutation`.
### Returns
`Omit`\<[`CreateMutationOptions`](../type-aliases/CreateMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
The same options object.
### See
[createMutation](createMutation.md) to run a mutation with these options.
### Example
```svelte
<script lang="ts">
import { mutationOptions, createMutation } from '@tanstack/svelte-query'
const createPostOptions = mutationOptions({
mutationFn: createPost,
})
const mutation = createMutation(() => createPostOptions)
</script>
<button onclick={() => mutation.mutate({ title: 'Hello' })}>Create</button>
```

View File

@@ -0,0 +1,32 @@
---
id: noop
title: noop
---
## Call Signature
```ts
function noop(): void;
```
Defined in: [packages/query-core/src/utils.ts:119](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L119)
A function that does nothing.
### Returns
`void`
## Call Signature
```ts
function noop(): undefined;
```
Defined in: [packages/query-core/src/utils.ts:120](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L120)
A function that does nothing.
### Returns
`undefined`

View File

@@ -0,0 +1,26 @@
---
id: partialMatchKey
title: partialMatchKey
---
```ts
function partialMatchKey(a, b): boolean;
```
Defined in: [packages/query-core/src/utils.ts:300](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L300)
Checks if key `b` partially matches with key `a`.
## Parameters
### a
readonly `unknown`[]
### b
readonly `unknown`[]
## Returns
`boolean`

View File

@@ -0,0 +1,157 @@
---
id: queryOptions
title: queryOptions
---
## Call Signature
```ts
function queryOptions<TQueryFnData, TError, TData, TQueryKey>(options): CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & object & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
```
Defined in: [packages/svelte-query/src/queryOptions.ts:68](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/queryOptions.ts#L68)
You can generally pass everything to `queryOptions` that you can also pass to `createQuery`. These options
can be shared across `createQuery` calls and imperative APIs such as `queryClient.query`. `options.queryKey`
is required and is the query key to generate options for.
This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`.
### Type Parameters
#### TQueryFnData
`TQueryFnData` = `unknown`
#### TError
`TError` = `Error`
#### TData
`TData` = `TQueryFnData`
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
### Parameters
#### options
[`DefinedInitialDataOptions`](../type-aliases/DefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
The [DefinedInitialDataOptions](../type-aliases/DefinedInitialDataOptions.md) to use — everything you can pass to `createQuery`,
with `initialData` set.
### Returns
[`CreateQueryOptions`](../type-aliases/CreateQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> & `object` & [`QueryKeyWithDataTag`](../type-aliases/QueryKeyWithDataTag.md)\<`TQueryKey`, `TQueryFnData`, `TError`\>
The same options object, typed so that `queryKey` carries the inferred data type.
### See
[createQuery](createQuery.md) to run a query with these options.
### Example
```svelte
<script lang="ts">
import { queryOptions, createQuery } from '@tanstack/svelte-query'
const postsOptions = queryOptions({
queryKey: ['posts'],
queryFn: fetchPosts,
initialData: [],
})
// `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails,
// so the list stays visible alongside the error.
const query = createQuery(() => postsOptions)
</script>
{#if query.isError}
<span>Error: {query.error.message}</span>
{/if}
<ul>
{#each query.data as post (post.id)}
<li>{post.title}</li>
{/each}
</ul>
```
## Call Signature
```ts
function queryOptions<TQueryFnData, TError, TData, TQueryKey>(options): CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & object & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
```
Defined in: [packages/svelte-query/src/queryOptions.ts:113](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/queryOptions.ts#L113)
You can generally pass everything to `queryOptions` that you can also pass to `createQuery`. These options
can be shared across `createQuery` calls and imperative APIs such as `queryClient.query`. `options.queryKey`
is required and is the query key to generate options for.
### Type Parameters
#### TQueryFnData
`TQueryFnData` = `unknown`
#### TError
`TError` = `Error`
#### TData
`TData` = `TQueryFnData`
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
### Parameters
#### options
[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
The [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use — everything you can pass to `createQuery`.
### Returns
[`CreateQueryOptions`](../type-aliases/CreateQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\> & `object` & [`QueryKeyWithDataTag`](../type-aliases/QueryKeyWithDataTag.md)\<`TQueryKey`, `TQueryFnData`, `TError`\>
The same options object, typed so that `queryKey` carries the inferred data type.
### See
[createQuery](createQuery.md) to run a query with these options.
### Example
A parameterized factory, so the same options object can be reused per `id`:
```svelte
<script lang="ts">
import { queryOptions, createQuery } from '@tanstack/svelte-query'
let { id }: { id: string } = $props()
const postOptions = (id: string) =>
queryOptions({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
})
const query = createQuery(() => postOptions(id))
</script>
{#if query.isPending}
Loading...
{:else if query.isError}
<span>Error: {query.error.message}</span>
{:else}
<h1>{query.data.title}</h1>
{/if}
```

View File

@@ -0,0 +1,41 @@
---
id: replaceEqualDeep
title: replaceEqualDeep
---
```ts
function replaceEqualDeep<T>(
a,
b,
depth?): T;
```
Defined in: [packages/query-core/src/utils.ts:339](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L339)
This function returns `a` if `b` is deeply equal.
If not, it will replace any deeply equal children of `b` with those of `a`.
This can be used for structural sharing between JSON values for example.
## Type Parameters
### T
`T`
## Parameters
### a
`unknown`
### b
`T`
### depth?
`number`
## Returns
`T`

View File

@@ -0,0 +1,22 @@
---
id: setIsRestoringContext
title: setIsRestoringContext
---
```ts
function setIsRestoringContext(isRestoring): void;
```
Defined in: [packages/svelte-query/src/context.ts:64](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/context.ts#L64)
Sets a `isRestoring` on Svelte's context
## Parameters
### isRestoring
`Box`\<`boolean`\>
## Returns
`void`

View File

@@ -0,0 +1,40 @@
---
id: setQueryClientContext
title: setQueryClientContext
---
```ts
function setQueryClientContext(client): void;
```
Defined in: [packages/svelte-query/src/context.ts:45](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/context.ts#L45)
Sets a `QueryClient` on Svelte's context, so it can be read with [getQueryClientContext](getQueryClientContext.md) (or
[useQueryClient](useQueryClient.md)) from any descendant component. `QueryClientProvider` wraps this — use it directly
only if you need to set the client from your own component instead.
## Parameters
### client
[`QueryClient`](../classes/QueryClient.md)
The `QueryClient` to make available to descendant components.
## Returns
`void`
## Example
```svelte
<script lang="ts">
import { QueryClient, QueryClientProvider } from '@tanstack/svelte-query'
const queryClient = new QueryClient()
</script>
<QueryClientProvider client={queryClient}>
...
</QueryClientProvider>
```

View File

@@ -0,0 +1,45 @@
---
id: shouldThrowError
title: shouldThrowError
---
```ts
function shouldThrowError<T>(throwOnError, params): boolean;
```
Defined in: [packages/query-core/src/utils.ts:576](https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L576)
Resolves a `throwOnError` option to a boolean.
If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller,
additional context such as the query or mutation) and its result is returned, allowing the throwing
behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined`
resolves to `false`).
## Type Parameters
### T
`T` *extends* (...`args`) => `boolean`
## Parameters
### throwOnError
`boolean` | `T` | `undefined`
### params
`Parameters`\<`T`\>
## Returns
`boolean`
## Example
```ts
const throwOnError =
query.state.error && typeof options.throwOnError === 'function'
? shouldThrowError(options.throwOnError, [query.state.error, query])
: options.throwOnError
```

View File

@@ -0,0 +1,61 @@
---
id: useHydrate
title: useHydrate
---
```ts
function useHydrate(
state?,
options?,
queryClient?): void;
```
Defined in: [packages/svelte-query/src/useHydrate.ts:33](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/useHydrate.ts#L33)
Adds a previously dehydrated `state` into the `queryClient` (from the nearest context, or the one
passed explicitly). If the client already contains data, the new queries will be intelligently merged based
on update timestamp. `HydrationBoundary` wraps this — use it directly only if you need to hydrate from your
own component instead.
## Parameters
### state?
`unknown`
The dehydrated state to hydrate into the cache, as produced by `dehydrate`.
### options?
[`HydrateOptions`](../interfaces/HydrateOptions.md)
[HydrateOptions](../interfaces/HydrateOptions.md) to control the hydration.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
## Returns
`void`
## Example
Server-side prefetch handed off to the client via `dehydrate` — `dehydratedState` would typically come
from a server load function that prefetched with `queryClient.query` and called `dehydrate(queryClient)`:
```svelte
<script lang="ts">
import { HydrationBoundary } from '@tanstack/svelte-query'
import type { DehydratedState } from '@tanstack/svelte-query'
import Posts from './Posts.svelte'
let { dehydratedState }: { dehydratedState: DehydratedState } = $props()
</script>
<HydrationBoundary state={dehydratedState}>
<Posts />
</HydrationBoundary>
```

View File

@@ -0,0 +1,60 @@
---
id: useIsFetching
title: useIsFetching
---
```ts
function useIsFetching(filters?, queryClient?): ReactiveValue<number>;
```
Defined in: [packages/svelte-query/src/useIsFetching.svelte.ts:40](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/useIsFetching.svelte.ts#L40)
## Parameters
### filters?
[`QueryFilters`](../interfaces/QueryFilters.md)\<readonly `unknown`[]\>
[QueryFilters](../interfaces/QueryFilters.md) to narrow down which queries to count. Omit to count every fetching
query.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
## Returns
`ReactiveValue`\<`number`\>
A reactive value — read `.current` to get how many matching queries are currently fetching.
## Examples
```svelte
<script lang="ts">
import { useIsFetching } from '@tanstack/svelte-query'
// How many queries matching the posts prefix are fetching?
const isFetchingPosts = useIsFetching({ queryKey: ['posts'] })
</script>
{#if isFetchingPosts.current}
<span>Refreshing posts...</span>
{/if}
```
A global loading indicator for any query fetching in the background, not just the ones on screen:
```svelte
<script lang="ts">
import { useIsFetching } from '@tanstack/svelte-query'
const isFetching = useIsFetching()
</script>
{#if isFetching.current}
<div>Queries are fetching in the background...</div>
{/if}
```

View File

@@ -0,0 +1,49 @@
---
id: useIsMutating
title: useIsMutating
---
```ts
function useIsMutating(filters?, queryClient?): ReactiveValue<number>;
```
Defined in: [packages/svelte-query/src/useIsMutating.svelte.ts:28](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/useIsMutating.svelte.ts#L28)
`useIsMutating` is an optional hook that returns the `number` of mutations that your application is
running (useful for app-wide loading indicators).
## Parameters
### filters?
[`MutationFilters`](../interfaces/MutationFilters.md)\<`unknown`, `Error`, `unknown`, `unknown`\>
[MutationFilters](../interfaces/MutationFilters.md) to narrow down which mutations to count.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
## Returns
`ReactiveValue`\<`number`\>
A reactive value — read `.current` to get how many matching mutations are currently running.
## Example
```svelte
<script lang="ts">
import { useIsMutating } from '@tanstack/svelte-query'
// How many mutations matching the posts prefix are in progress?
const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
</script>
{#if isMutatingPosts.current}
<span>Saving posts...</span>
{/if}
```

View File

@@ -0,0 +1,14 @@
---
id: useIsRestoring
title: useIsRestoring
---
```ts
function useIsRestoring(): Box<boolean>;
```
Defined in: [packages/svelte-query/src/useIsRestoring.ts:4](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/useIsRestoring.ts#L4)
## Returns
`Box`\<`boolean`\>

View File

@@ -0,0 +1,104 @@
---
id: useMutationState
title: useMutationState
---
```ts
function useMutationState<TResult, TMutation>(options, queryClient?): TResult[];
```
Defined in: [packages/svelte-query/src/useMutationState.svelte.ts:99](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/useMutationState.svelte.ts#L99)
`useMutationState` gives you access to all mutations (matching the given `filters`), including ones that
were created by a different component or hook instance, or even ones no longer mounted.
## Type Parameters
### TResult
`TResult` = [`MutationState`](../interfaces/MutationState.md)\<`unknown`, `Error`, `unknown`, `unknown`\>
### TMutation
`TMutation` *extends* [`Mutation`](../classes/Mutation.md)\<`any`, `any`, `any`, `any`\> = [`MutationTypeFromResult`](../type-aliases/MutationTypeFromResult.md)\<`TResult`\>
## Parameters
### options
[`MutationStateOptions`](../type-aliases/MutationStateOptions.md)\<`TResult`, `TMutation`\> = `{}`
The `filters` to narrow down matched mutations, and an optional `select` to transform the
mutation state.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
## Returns
`TResult`[]
An Array of whatever `select` returns for each matching mutation.
## Examples
Get all variables of all running mutations:
```svelte
<script lang="ts">
import { useMutationState } from '@tanstack/svelte-query'
const pendingVariables = useMutationState({
filters: { status: 'pending' },
select: (mutation) => mutation.state.variables,
})
</script>
{pendingVariables.length} posts saving...
```
Get all data for specific mutations via the `mutationKey`:
```svelte
<script lang="ts">
import { createMutation, useMutationState } from '@tanstack/svelte-query'
const mutationKey = ['posts']
// Some mutation that we want to get the state for
const mutation = createMutation(() => ({
mutationKey,
mutationFn: createPosts,
}))
const savedPosts = useMutationState({
// this mutation key needs to match the mutation key of the given mutation (see above)
filters: { mutationKey, status: 'success' },
select: (mutation) => mutation.state.data,
})
</script>
<button onclick={() => mutation.mutate(['New Post'])}>
Create post ({savedPosts.length} saved so far)
</button>
```
Access the latest mutation data via the `mutationKey`. Each invocation of `mutate` adds a new entry to the
mutation cache for `gcTime` milliseconds — check the last item that `useMutationState` returns to get the
latest successful mutation (the `status: 'success'` filter above excludes pending/errored ones):
```svelte
<script lang="ts">
import { useMutationState } from '@tanstack/svelte-query'
const savedPosts = useMutationState({
filters: { mutationKey: ['posts'], status: 'success' },
select: (mutation) => mutation.state.data,
})
const latestSavedPost = $derived(savedPosts[savedPosts.length - 1])
</script>
{latestSavedPost ? 'Saved' : 'Nothing saved yet'}
```

View File

@@ -0,0 +1,20 @@
---
id: useQueryClient
title: useQueryClient
---
```ts
function useQueryClient(queryClient?): QueryClient;
```
Defined in: [packages/svelte-query/src/useQueryClient.ts:4](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/useQueryClient.ts#L4)
## Parameters
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
## Returns
[`QueryClient`](../classes/QueryClient.md)