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,137 @@
---
id: devtools
title: Devtools
---
Wave your hands in the air and shout hooray because Preact Query comes with dedicated devtools! 🥳
When you begin your Preact Query journey, you'll want these devtools by your side. They help visualize all of the inner workings of Preact Query and will likely save you hours of debugging if you find yourself in a pinch!
> For Chrome, Firefox, and Edge users: Third-party browser extensions are available for debugging TanStack Query directly in browser DevTools. These provide the same functionality as the framework-specific devtools packages:
>
> - <img alt="Chrome logo" src="https://www.google.com/chrome/static/images/chrome-logo.svg" width="16" height="16" class="inline mr-1 not-prose" /> <a href="https://chromewebstore.google.com/detail/tanstack-query-devtools/annajfchloimdhceglpgglpeepfghfai">Devtools for Chrome</a>
> - <img alt="Firefox logo" src="https://upload.wikimedia.org/wikipedia/commons/a/a0/Firefox_logo%2C_2019.svg" width="16" height="16" class="inline mr-1 not-prose" /> <a href="https://addons.mozilla.org/en-US/firefox/addon/tanstack-query-devtools/">Devtools for Firefox</a>
> - <img alt="Edge logo" src="https://upload.wikimedia.org/wikipedia/commons/9/98/Microsoft_Edge_logo_%282019%29.svg" width="16" height="16" class="inline mr-1 not-prose" /> <a href="https://microsoftedge.microsoft.com/addons/detail/tanstack-query-devtools/edmdpkgkacmjopodhfolmphdenmddobj">Devtools for Edge</a>
## Install and Import the Devtools
The devtools are a separate package that you need to install:
```bash
npm i @tanstack/preact-query-devtools
```
or
```bash
pnpm add @tanstack/preact-query-devtools
```
or
```bash
yarn add @tanstack/preact-query-devtools
```
or
```bash
bun add @tanstack/preact-query-devtools
```
You can import the devtools like this:
```tsx
import { PreactQueryDevtools } from '@tanstack/preact-query-devtools'
```
By default, Preact Query Devtools are only included in bundles when `process.env.NODE_ENV === 'development'`, so you don't need to worry about excluding them during a production build.
## Floating Mode
Floating Mode will mount the devtools as a fixed, floating element in your app and provide a toggle in the corner of the screen to show and hide the devtools. This toggle state will be stored and remembered in localStorage across reloads.
Place the following code as high in your Preact app as you can. The closer it is to the root of the page, the better it will work!
```tsx
import { PreactQueryDevtools } from '@tanstack/preact-query-devtools'
function App() {
return (
<QueryClientProvider client={queryClient}>
{/* The rest of your application */}
<PreactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
)
}
```
### Options
- `initialIsOpen: boolean`
- Set this `true` if you want the dev tools to default to being open
- `buttonPosition?: "top-left" | "top-right" | "bottom-left" | "bottom-right" | "relative"`
- Defaults to `bottom-right`
- The position of the TanStack logo to open and close the devtools panel
- `position?: "top" | "bottom" | "left" | "right"`
- Defaults to `bottom`
- The position of the Preact Query devtools panel
- `client?: QueryClient`,
- Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
- `errorTypes?: { name: string; initializer: (query: Query) => TError}[]`
- Use this to predefine some errors that can be triggered on your queries. Initializer will be called (with the specific query) when that error is toggled on from the UI. It must return an Error.
- `styleNonce?: string`
- Use this to pass a nonce to the style tag that is added to the document head. This is useful if you are using a Content Security Policy (CSP) nonce to allow inline styles.
- `shadowDOMTarget?: ShadowRoot`
- Default behavior will apply the devtool's styles to the head tag within the DOM.
- Use this to pass a shadow DOM target to the devtools so that the styles will be applied within the shadow DOM instead of within the head tag in the light DOM.
- `theme?: "light" | "dark" | "system"`
- Defaults to `system`.
- Set this to change the theme of the devtools panel.
## Embedded Mode
Embedded mode will show the development tools as a fixed element in your application, so you can use our panel in your own development tools.
Place the following code as high in your Preact app as you can. The closer it is to the root of the page, the better it will work!
```tsx
import { useState } from 'preact/hooks'
import { PreactQueryDevtoolsPanel } from '@tanstack/preact-query-devtools'
function App() {
const [isOpen, setIsOpen] = useState(false)
return (
<QueryClientProvider client={queryClient}>
{/* The rest of your application */}
<button
onClick={() => setIsOpen(!isOpen)}
>{`${isOpen ? 'Close' : 'Open'} the devtools panel`}</button>
{isOpen && <PreactQueryDevtoolsPanel onClose={() => setIsOpen(false)} />}
</QueryClientProvider>
)
}
```
### Options
- `style?: CSSProperties`
- Custom styles for the devtools panel
- Default: `{ height: '500px' }`
- Example: `{ height: '100%' }`
- Example: `{ height: '100%', width: '100%' }`
- `onClose?: () => void`
- Callback function that is called when the devtools panel is closed
- `client?: QueryClient`,
- Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
- `errorTypes?: { name: string; initializer: (query: Query) => TError}[]`
- Use this to predefine some errors that can be triggered on your queries. Initializer will be called (with the specific query) when that error is toggled on from the UI. It must return an Error.
- `styleNonce?: string`
- Use this to pass a nonce to the style tag that is added to the document head. This is useful if you are using a Content Security Policy (CSP) nonce to allow inline styles.
- `shadowDOMTarget?: ShadowRoot`
- Default behavior will apply the devtool's styles to the head tag within the DOM.
- Use this to pass a shadow DOM target to the devtools so that the styles will be applied within the shadow DOM instead of within the head tag in the light DOM.
- `theme?: "light" | "dark" | "system"`
- Defaults to `system`.
- Set this to change the theme of the devtools panel.

View File

@@ -0,0 +1,6 @@
---
id: graphql
title: GraphQL
ref: docs/framework/react/graphql.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: background-fetching-indicators
title: Background Fetching Indicators
ref: docs/framework/react/guides/background-fetching-indicators.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: caching
title: Caching Examples
ref: docs/framework/react/guides/caching.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: default-query-function
title: Default Query Function
ref: docs/framework/react/guides/default-query-function.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: dependent-queries
title: Dependent Queries
ref: docs/framework/react/guides/dependent-queries.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,56 @@
---
id: disabling-queries
title: Disabling/Pausing Queries
ref: docs/framework/react/guides/disabling-queries.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---
[//]: # 'Example2'
```tsx
function Todos() {
const [filter, setFilter] = useState('')
const { data } = useQuery({
queryKey: ['todos', filter],
queryFn: () => fetchTodos(filter),
// ⬇️ disabled as long as the filter is empty
enabled: !!filter,
})
return (
<div>
// 🚀 applying the filter will enable and execute the query
<FiltersForm onApply={setFilter} />
{data && <TodosTable data={data} />}
</div>
)
}
```
[//]: # 'Example2'
[//]: # 'Example3'
```tsx
import { skipToken, useQuery } from '@tanstack/preact-query'
function Todos() {
const [filter, setFilter] = useState<string | undefined>()
const { data } = useQuery({
queryKey: ['todos', filter],
// ⬇️ disabled as long as the filter is undefined or empty
queryFn: filter ? () => fetchTodos(filter) : skipToken,
})
return (
<div>
// 🚀 applying the filter will enable and execute the query
<FiltersForm onApply={setFilter} />
{data && <TodosTable data={data} />}
</div>
)
}
```
[//]: # 'Example3'

View File

@@ -0,0 +1,6 @@
---
id: does-this-replace-client-state
title: Does TanStack Query replace Redux, MobX or other global state managers?
ref: docs/framework/react/guides/does-this-replace-client-state.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: filters
title: Filters
ref: docs/framework/react/guides/filters.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: important-defaults
title: Important Defaults
ref: docs/framework/react/guides/important-defaults.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,65 @@
---
id: infinite-queries
title: Infinite Queries
ref: docs/framework/react/guides/infinite-queries.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---
[//]: # 'Example'
```tsx
import { useInfiniteQuery } from '@tanstack/preact-query'
function Projects() {
const fetchProjects = async ({ pageParam }) => {
const res = await fetch('/api/projects?cursor=' + pageParam)
return res.json()
}
const {
data,
error,
fetchNextPage,
hasNextPage,
isFetching,
isFetchingNextPage,
status,
} = useInfiniteQuery({
queryKey: ['projects'],
queryFn: fetchProjects,
initialPageParam: 0,
getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
})
return status === 'pending' ? (
<p>Loading...</p>
) : status === 'error' ? (
<p>Error: {error.message}</p>
) : (
<>
{data.pages.map((group, i) => (
<div key={i}>
{group.data.map((project) => (
<p key={project.id}>{project.name}</p>
))}
</div>
))}
<div>
<button
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetching}
>
{isFetchingNextPage
? 'Loading more...'
: hasNextPage
? 'Load More'
: 'Nothing more to load'}
</button>
</div>
<div>{isFetching && !isFetchingNextPage ? 'Fetching...' : null}</div>
</>
)
}
```
[//]: # 'Example'

View File

@@ -0,0 +1,6 @@
---
id: initial-query-data
title: Initial Query Data
ref: docs/framework/react/guides/initial-query-data.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: invalidations-from-mutations
title: Invalidations from Mutations
ref: docs/framework/react/guides/invalidations-from-mutations.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,11 @@
---
id: mutations
title: Mutations
ref: docs/framework/react/guides/mutations.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---
[//]: # 'Info1'
[//]: # 'Info1'
[//]: # 'Example2'
[//]: # 'Example2'

View File

@@ -0,0 +1,6 @@
---
id: network-mode
title: Network Mode
ref: docs/framework/react/guides/network-mode.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: optimistic-updates
title: Optimistic Updates
ref: docs/framework/react/guides/optimistic-updates.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,64 @@
---
id: paginated-queries
title: Paginated / Lagged Queries
ref: docs/framework/react/guides/paginated-queries.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---
[//]: # 'Example2'
```tsx
import { keepPreviousData, useQuery } from '@tanstack/preact-query'
import { useState } from 'preact/hooks'
function Todos() {
const [page, setPage] = useState(0)
const fetchProjects = (page = 0) =>
fetch('/api/projects?page=' + page).then((res) => res.json())
const { isPending, isError, error, data, isFetching, isPlaceholderData } =
useQuery({
queryKey: ['projects', page],
queryFn: () => fetchProjects(page),
placeholderData: keepPreviousData,
})
return (
<div>
{isPending ? (
<div>Loading...</div>
) : isError ? (
<div>Error: {error.message}</div>
) : (
<div>
{data.projects.map((project) => (
<p key={project.id}>{project.name}</p>
))}
</div>
)}
<span>Current Page: {page + 1}</span>
<button
onClick={() => setPage((old) => Math.max(old - 1, 0))}
disabled={page === 0}
>
Previous Page
</button>
<button
onClick={() => {
if (!isPlaceholderData && data.hasMore) {
setPage((old) => old + 1)
}
}}
// Disable the Next Page button until we know a next page is available
disabled={isPlaceholderData || !data?.hasMore}
>
Next Page
</button>
{isFetching ? <span> Loading...</span> : null}
</div>
)
}
```
[//]: # 'Example2'

View File

@@ -0,0 +1,12 @@
---
id: parallel-queries
title: Parallel Queries
ref: docs/framework/react/guides/parallel-queries.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---
[//]: # 'Info'
> When using Preact Query with compat's Suspense, this pattern of parallelism does not work, since the first query would throw a promise internally and would suspend the component before the other queries run. To get around this, you'll either need to use the `useSuspenseQueries` hook (which is suggested) or orchestrate your own parallelism with separate components for each `useSuspenseQuery` instance.
[//]: # 'Info'

View File

@@ -0,0 +1,6 @@
---
id: placeholder-query-data
title: Placeholder Query Data
ref: docs/framework/react/guides/placeholder-query-data.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: polling
title: Polling
ref: docs/framework/react/guides/polling.md
replace: { '@tanstack/react-query': '@tanstack/preact-query' }
---

View File

@@ -0,0 +1,51 @@
---
id: prefetching
title: Prefetching & Router Integration
ref: docs/framework/react/guides/prefetching.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---
[//]: # 'ExampleConditionally1'
```tsx
// This lazy loads the GraphFeedItem component, meaning
// it wont start loading until something renders it
import { lazy } from 'preact/iso'
const GraphFeedItem = lazy(() => import('./GraphFeedItem'))
function Feed() {
const { data, isPending } = useQuery({
queryKey: ['feed'],
queryFn: getFeed,
})
if (isPending) {
return 'Loading feed...'
}
return (
<>
{data.map((feedItem) => {
if (feedItem.type === 'GRAPH') {
return <GraphFeedItem key={feedItem.id} feedItem={feedItem} />
}
return <StandardFeedItem key={feedItem.id} feedItem={feedItem} />
})}
</>
)
}
// GraphFeedItem.tsx
function GraphFeedItem({ feedItem }) {
const { data, isPending } = useQuery({
queryKey: ['graph', feedItem.id],
queryFn: getGraphDataById,
})
...
}
```
[//]: # 'ExampleConditionally1'

View File

@@ -0,0 +1,6 @@
---
id: queries
title: Queries
ref: docs/framework/react/guides/queries.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: query-cancellation
title: Query Cancellation
ref: docs/framework/react/guides/query-cancellation.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: query-functions
title: Query Functions
ref: docs/framework/react/guides/query-functions.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: query-invalidation
title: Query Invalidation
ref: docs/framework/react/guides/query-invalidation.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: query-keys
title: Query Keys
ref: docs/framework/react/guides/query-keys.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: query-options
title: Query Options
ref: docs/framework/react/guides/query-options.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: query-retries
title: Query Retries
ref: docs/framework/react/guides/query-retries.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: render-optimizations
title: Render Optimizations
ref: docs/framework/react/guides/render-optimizations.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,50 @@
---
id: request-waterfalls
title: Performance & Request Waterfalls
ref: docs/framework/react/guides/request-waterfalls.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---
[//]: # 'LazyExample'
```tsx
import { lazy } from 'preact/iso'
// This lazy loads the GraphFeedItem component, meaning
// it wont start loading until something renders it
const GraphFeedItem = lazy(() => import('./GraphFeedItem'))
function Feed() {
const { data, isPending } = useQuery({
queryKey: ['feed'],
queryFn: getFeed,
})
if (isPending) {
return 'Loading feed...'
}
return (
<>
{data.map((feedItem) => {
if (feedItem.type === 'GRAPH') {
return <GraphFeedItem key={feedItem.id} feedItem={feedItem} />
}
return <StandardFeedItem key={feedItem.id} feedItem={feedItem} />
})}
</>
)
}
// GraphFeedItem.tsx
function GraphFeedItem({ feedItem }) {
const { data, isPending } = useQuery({
queryKey: ['graph', feedItem.id],
queryFn: getGraphDataById,
})
...
}
```
[//]: # 'LazyExample'

View File

@@ -0,0 +1,5 @@
---
id: scroll-restoration
title: Scroll Restoration
ref: docs/framework/react/guides/scroll-restoration.md
---

View File

@@ -0,0 +1,365 @@
---
id: ssr
title: Server Rendering & Hydration
---
In this guide you'll learn how to use Preact Query with server rendering.
See the guide on [Prefetching & Router Integration](./prefetching.md) for some background. You might also want to check out the [Performance & Request Waterfalls guide](./request-waterfalls.md) before that.
## Server Rendering & Preact Query
So what is server rendering anyway? The rest of this guide will assume you are familiar with the concept, but let's spend some time to look at how it relates to Preact Query. Server rendering is the act of generating the initial html on the server, so that the user has some content to look at as soon as the page loads. This can happen on demand when a page is requested (SSR). It can also happen ahead of time either because a previous request was cached, or at build time (SSG).
If you've read the [Performance & Request Waterfalls guide](./request-waterfalls.md), you might remember this:
```
1. |-> Markup (without content)
2. |-> JS
3. |-> Query
```
With a client rendered application, these are the minimum 3 server roundtrips you will need to make before getting any content on the screen for the user. One way of viewing server rendering is that it turns the above into this:
```
1. |-> Markup (with content AND initial data)
2. |-> JS
```
As soon as **1.** is complete, the user can see the content and when **2.** finishes, the page is interactive and clickable. Because the markup also contains the initial data we need, step **3.** does not need to run on the client at all, at least until you want to revalidate the data for some reason.
This is all from the clients perspective. On the server, we need to **prefetch** that data before we generate/render the markup, we need to **dehydrate** that data into a serializable format we can embed in the markup, and on the client we need to **hydrate** that data into a Preact Query cache so we can avoid doing a new fetch on the client.
Read on to learn how to implement these three steps with Preact Query.
## A quick note on Suspense
This guide uses the regular `useQuery` API. While we don't necessarily recommend it, it is possible to replace this with `useSuspenseQuery` instead **as long as you always prefetch all your queries**. The upside is that you get to use `<Suspense>` for loading states on the client.
If you do forget to prefetch a query when you are using `useSuspenseQuery`, the consequences will depend on your setup. In some cases, the data will Suspend and get fetched on the server but never be hydrated to the client, where it will fetch again. In these cases you will get a markup hydration mismatch, because the server and the client tried to render different things.
## Initial setup
The first step of using Preact Query is always to create a `queryClient` and wrap the application in a `<QueryClientProvider>`. When doing server rendering, it's important to create the `queryClient` instance **inside of your app**, in Preact state (an instance ref works fine too). **This ensures that data is not shared between different users and requests**, while still only creating the `queryClient` once per component lifecycle.
```tsx
import { QueryClient, QueryClientProvider } from '@tanstack/preact-query'
import { useState } from 'preact/hooks'
// NEVER DO THIS ON THE SERVER:
// const queryClient = new QueryClient()
//
// Creating the queryClient at the module root level makes the cache shared
// between all requests and means _all_ data gets passed to _all_ users.
// Besides being bad for performance, this also leaks any sensitive data.
// (On the client this is fine, since there's only ever one visitor per page.)
export function App({ children }) {
// Instead do this, which ensures each request has its own cache:
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
// With SSR, we usually want to set some default staleTime
// above 0 to avoid refetching immediately on the client
staleTime: 60 * 1000,
},
},
}),
)
return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
```
## Get started fast with `initialData`
The quickest way to get started is to not involve Preact Query at all when it comes to prefetching and not use the `dehydrate`/`hydrate` APIs. What you do instead is passing the raw data in as the `initialData` option to `useQuery`:
```tsx
function Posts({ posts }) {
const { data } = useQuery({
queryKey: ['posts'],
queryFn: getPosts,
initialData: posts,
})
// ...
}
```
The setup is minimal and this can be a quick solution for some cases, but there are a **few tradeoffs to consider** when compared to the full approach:
- If you are calling `useQuery` in a component deeper down in the tree you need to pass the `initialData` down to that point
- If you are calling `useQuery` with the same query in multiple locations, passing `initialData` to only one of them can be brittle and break when your app changes. If you remove or move the component that has the `useQuery` with `initialData`, the more deeply nested `useQuery` might no longer have any data. Passing `initialData` to **all** queries that need it can also be cumbersome.
- There is no way to know at what time the query was fetched on the server, so `dataUpdatedAt` and determining if the query needs refetching is based on when the page loaded instead
- If there is already data in the cache for a query, `initialData` will never overwrite this data, **even if the new data is fresher than the old one**.
Setting up the full hydration solution is straightforward and does not have these drawbacks, this will be the focus for the rest of the documentation.
## Using the Hydration APIs
With just a little more setup, you can use a `queryClient` to prefetch queries during a server render pass, serialize that `queryClient` and send it down with the initial markup, then reuse it to hydrate the client render. This avoids the drawbacks above. At a general level these are the extra steps:
- On the server, create a `const queryClient = new QueryClient(options)`
- Do `await queryClient.query(...)` for each query you want to prefetch
- You want to use `await Promise.all(...)` to fetch the queries in parallel when possible
- It's fine to have queries that aren't prefetched. These wont be server rendered, instead they will be fetched on the client after the application is interactive. This can be great for content that are shown only after user interaction, or is far down on the page to avoid blocking more critical content.
- Call `dehydrate(queryClient)` and embed the result in the markup you send to the client, alongside the html produced by `renderToString`
- On the client, wrap your tree with `<HydrationBoundary state={dehydratedState}>`, where `dehydratedState` is parsed back out of the embedded markup
> An interesting detail is that there are actually _two_ `queryClient`s involved on the server: one that prefetches, and one that renders. The prefetching client fetches the queries and gets `dehydrate`d; its dehydrated state is then `hydrate`d into a fresh render client, which is the one you actually pass to `<QueryClientProvider>` for `renderToString`. On the client, a third `queryClient` is created and hydrated with the same dehydrated state via `<HydrationBoundary>`, so all three start from the same data and produce the same markup.
### Full example with `preact-render-to-string`
Server entry point:
```tsx
import { renderToString } from 'preact-render-to-string'
import {
QueryCache,
QueryClient,
QueryClientProvider,
dehydrate,
hydrate,
noop,
} from '@tanstack/preact-query'
function makeQueryClient() {
return new QueryClient({
queryCache: new QueryCache(),
defaultOptions: {
queries: {
// With SSR, we usually want to set some default staleTime
// above 0 to avoid refetching immediately on the client
staleTime: 60 * 1000,
},
},
})
}
export async function render(url) {
// The prefetching client: only used to fetch and dehydrate
const prefetchClient = makeQueryClient()
await prefetchClient
.query({
queryKey: ['posts'],
queryFn: getPosts,
})
.catch(noop)
const dehydratedState = dehydrate(prefetchClient)
// The render client: hydrated with the same state, used for renderToString
const renderClient = makeQueryClient()
hydrate(renderClient, dehydratedState)
const appHtml = renderToString(
<QueryClientProvider client={renderClient}>
<App />
</QueryClientProvider>,
)
// Embed both the markup and the dehydrated state in the html you send down.
// Use a safe serializer here (see Serialization below), NOT JSON.stringify,
// since raw JSON.stringify output can break out of the <script> tag:
// e.g. `<div id="app">${appHtml}</div><script>window.__DEHYDRATED_STATE__ = ${serialize(dehydratedState)}</script>`
return { appHtml, dehydratedState }
}
```
Client entry point:
```tsx
import { hydrate as preactHydrate } from 'preact'
import { useState } from 'preact/hooks'
import {
HydrationBoundary,
QueryClient,
QueryClientProvider,
} from '@tanstack/preact-query'
function makeQueryClient() {
return new QueryClient({
defaultOptions: {
queries: {
// With SSR, we usually want to set some default staleTime
// above 0 to avoid refetching immediately on the client
staleTime: 60 * 1000,
},
},
})
}
function App({ dehydratedState }) {
const [queryClient] = useState(() => makeQueryClient())
return (
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={dehydratedState}>
<Posts />
</HydrationBoundary>
</QueryClientProvider>
)
}
// Read back and deserialize whatever you embedded on the server,
// e.g. `window.__DEHYDRATED_STATE__`
preactHydrate(
<App dehydratedState={window.__DEHYDRATED_STATE__} />,
document.getElementById('app'),
)
```
Anywhere inside the tree:
```tsx
function Posts() {
// This useQuery could just as well happen in some deeper child to <App>,
// data will be available immediately either way
const { data } = useQuery({ queryKey: ['posts'], queryFn: getPosts })
// This query was not prefetched on the server and will not start
// fetching until on the client, both patterns are fine to mix
const { data: commentsData } = useQuery({
queryKey: ['posts-comments'],
queryFn: getComments,
})
// ...
}
```
## Prefetching dependent queries
Over in the Prefetching guide we learned how to [prefetch dependent queries](./prefetching.md#dependent-queries-code-splitting), but how do we do this on the server? Consider the following code, taken from the [Dependent Queries guide](./dependent-queries.md):
```tsx
// Get the user
const { data: user } = useQuery({
queryKey: ['user', email],
queryFn: getUserByEmail,
})
const userId = user?.id
// Then get the user's projects
const {
status,
fetchStatus,
data: projects,
} = useQuery({
queryKey: ['projects', userId],
queryFn: getProjectsByUser,
// The query will not execute until the userId exists
enabled: !!userId,
})
```
How would we prefetch this so it can be server rendered? Here's an example:
```tsx
const queryClient = new QueryClient()
const user = await queryClient.query({
queryKey: ['user', email],
queryFn: getUserByEmail,
})
if (user?.id) {
await queryClient.query({
queryKey: ['projects', user.id],
queryFn: getProjectsByUser,
})
}
const dehydratedState = dehydrate(queryClient)
```
This can get more complex of course, but since prefetching just happens with plain JavaScript, you can use the full power of the language to build your logic. Make sure you prefetch all queries that you want to be server rendered.
## Error handling
Preact Query defaults to a graceful degradation strategy. This means:
- `dehydrate(...)` only includes successful queries, not failed ones
- We can intentionally ignore the returned promise from `void queryClient.query(...)` and add `.catch(noop)` to swallow any errors, so surrounding server code will not observe query errors
This will lead to any failed queries being retried on the client and that the server rendered output will include loading states instead of the full content.
While a good default, sometimes this is not what you want. When critical content is missing, you might want to respond with a 404 or 500 status code depending on the situation. For these cases, use `await queryClient.query(...)` without the noop catch, which will throw errors when it fails, letting you handle things in a suitable way.
```tsx
let result
try {
result = await queryClient.query(...)
} catch (error) {
// Handle the error in whatever way fits your server setup
}
// You might also want to check and handle any invalid `result` here
```
If you for some reason want to include failed queries in the dehydrated state to avoid retries, you can use the option `shouldDehydrateQuery` to override the default function and implement your own logic:
```tsx
dehydrate(queryClient, {
shouldDehydrateQuery: (query) => {
// This will include all queries, including failed ones,
// but you can also implement your own logic by inspecting `query`
return true
},
})
```
## Serialization
The `dehydrate(queryClient)` result needs to be serialized so it can be embedded into the markup and transported to the client, then parsed back out before being passed to `<HydrationBoundary state={...}>`.
Your first instinct might be to use `JSON.stringify(dehydratedState)`, but because this doesn't escape things like `<script>alert('Oh no..')</script>` by default, this can easily lead to **XSS-vulnerabilities** in your application. Instead we recommend using a library like [Serialize JavaScript](https://github.com/yahoo/serialize-javascript) or [devalue](https://github.com/Rich-Harris/devalue) which are both safe against XSS injections out of the box.
By default, plain `JSON.stringify`/`JSON.parse` also do not support `undefined`, `Error`, `Date`, `Map`, `Set`, `BigInt`, `Infinity`, `NaN`, `-0`, regular expressions etc. This also means that you can not return any of these things from your queries unless your serializer supports them. If returning these values is something you want, check out [superjson](https://github.com/blitz-js/superjson) or similar packages (note that superjson **does not** escape values by itself, so you still need an extra step for escaping the output).
Instead of serializing the whole `dehydratedState` from the outside, you can also let Preact Query do this per-query by configuring `dehydrate.serializeData`/`hydrate.deserializeData` on the `QueryClient`:
```tsx
const queryClient = new QueryClient({
defaultOptions: {
dehydrate: {
serializeData: serialize,
},
hydrate: {
deserializeData: deserialize,
},
},
})
```
This transforms each query's `data` on the way out of `dehydrate` and on the way into `hydrate`, so `serialize`/`deserialize` only ever need to handle the shape of your query data, not the full dehydrated state. As with any custom serializer, make sure it's safe against XSS if you end up embedding its output directly into markup.
## Tips, Tricks and Caveats
### Staleness is measured from when the query was fetched on the server
A query is considered stale depending on when it was `dataUpdatedAt`. A caveat here is that the server needs to have the correct time for this to work properly, but UTC time is used, so timezones do not factor into this.
Because `staleTime` defaults to `0`, queries will be refetched in the background on page load by default. You might want to use a higher `staleTime` to avoid this double fetching, especially if you don't cache your markup.
This refetching of stale queries is a perfect match when caching markup in a CDN! You can set the cache time of the page itself decently high to avoid having to re-render pages on the server, but configure the `staleTime` of the queries lower to make sure data is refetched in the background as soon as a user visits the page. Maybe you want to cache the pages for a week, but refetch the data automatically on page load if it's older than a day?
### High memory consumption on server
In case you are creating the `QueryClient` for every request, Preact Query creates the isolated cache for this client, which is preserved in memory for the `gcTime` period. That may lead to high memory consumption on server in case of high number of requests during that period.
On the server, `gcTime` defaults to `Infinity` which disables manual garbage collection and will automatically clear memory once a request has finished. If you are explicitly setting a non-Infinity `gcTime` then you will be responsible for clearing the cache early.
Avoid setting `gcTime` to `0` as it may result in a hydration error. This occurs because the [Hydration Boundary](../reference/functions/HydrationBoundary.md) places necessary data into the cache for rendering, but if the garbage collector removes the data before the rendering completes, issues may arise. If you require a shorter `gcTime`, we recommend setting it to `2 * 1000` to allow sufficient time for the app to reference the data.
To clear the cache after it is not needed and to lower memory consumption, you can add a call to [`queryClient.clear()`](../reference/classes/QueryClient.md#clear) after the request is handled and dehydrated state has been sent to the client.
Alternatively, you can set a smaller `gcTime`.

View File

@@ -0,0 +1,87 @@
---
id: suspense
title: Suspense
ref: docs/framework/react/guides/suspense.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---
[//]: # 'Info'
When using suspense mode, `status` states and `error` objects are not needed and are then replaced by usage of the `Suspense` component from `preact/compat` (including the use of the `fallback` prop and error boundaries for catching errors). Please read the [Resetting Error Boundaries](#resetting-error-boundaries) section for more information on how to set up suspense mode.
[//]: # 'Info'
[//]: # 'PlaceholderData'
`placeholderData` also doesn't exist for this Query.
[//]: # 'PlaceholderData'
[//]: # 'ExampleResetComponent'
Preact does not ship an error boundary component, but one can be built with the [`useErrorBoundary`](https://preactjs.com/guide/v10/hooks/#useerrorboundary) hook:
```tsx
import { QueryErrorResetBoundary } from '@tanstack/preact-query'
import { useErrorBoundary } from 'preact/hooks'
function ErrorBoundary({ children, onReset, fallbackRender }) {
const [error, resetError] = useErrorBoundary()
if (error) {
return fallbackRender({
error,
resetErrorBoundary: () => {
onReset()
resetError()
},
})
}
return children
}
const App = () => (
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
There was an error!
<button onClick={() => resetErrorBoundary()}>Try again</button>
</div>
)}
>
<Page />
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
)
```
[//]: # 'ExampleResetComponent'
[//]: # 'ExampleResetHook'
```tsx
import { useQueryErrorResetBoundary } from '@tanstack/preact-query'
const App = () => {
const { reset } = useQueryErrorResetBoundary()
return (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
There was an error!
<button onClick={() => resetErrorBoundary()}>Try again</button>
</div>
)}
>
<Page />
</ErrorBoundary>
)
}
```
[//]: # 'ExampleResetHook'
[//]: # 'Streaming'
[//]: # 'Streaming'

View File

@@ -0,0 +1,48 @@
---
id: testing
title: Testing
ref: docs/framework/react/guides/testing.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---
[//]: # 'Install'
Writing unit tests for these custom hooks can be done by means of the [Preact Testing Library](https://github.com/testing-library/preact-testing-library), which provides `renderHook` and re-exports the `@testing-library/dom` helpers such as `waitFor`.
Install this by running:
```sh
npm install @testing-library/preact --save-dev
```
[//]: # 'Install'
[//]: # 'ExampleFirstTest'
```tsx
import { renderHook, waitFor } from '@testing-library/preact'
const queryClient = new QueryClient()
const wrapper = ({ children }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
const { result } = renderHook(() => useCustomHook(), { wrapper })
await waitFor(() => expect(result.current.isSuccess).toBe(true))
expect(result.current.data).toEqual('Hello')
```
[//]: # 'ExampleFirstTest'
[//]: # 'NoteWaitFor1'
Here we are making use of `waitFor` and waiting until the query status indicates that the request has succeeded. This way we know that our hook has finished and should have the correct data.
[//]: # 'NoteWaitFor1'
[//]: # 'NoteWaitFor2'
[//]: # 'NoteWaitFor2'
[//]: # 'FurtherReading'
For additional tips and an alternative setup using `mock-service-worker`, have a look at [TkDodo's article on testing](https://tkdodo.eu/blog/testing-react%2Dquery). It's written for a different framework adapter, but the same approach applies here.
[//]: # 'FurtherReading'

View File

@@ -0,0 +1,5 @@
---
id: updates-from-mutation-responses
title: Updates from Mutation Responses
ref: docs/framework/react/guides/updates-from-mutation-responses.md
---

View File

@@ -0,0 +1,9 @@
---
id: window-focus-refetching
title: Window Focus Refetching
ref: docs/framework/react/guides/window-focus-refetching.md
replace: { 'react-query': 'preact-query' }
---
[//]: # 'ReactNative'
[//]: # 'ReactNative'

View File

@@ -0,0 +1,22 @@
---
id: installation
title: Installation
ref: docs/framework/react/installation.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---
[//]: # 'Compatibility'
> Wanna give it a spin before you download? Try out the [simple](./examples/simple) example
[//]: # 'Compatibility'
[//]: # 'CDNExample'
```html
<script type="module">
import { render } from 'https://esm.sh/preact@10.23.1'
import { QueryClient } from 'https://esm.sh/@tanstack/preact-query'
</script>
```
[//]: # 'CDNExample'

View File

@@ -0,0 +1,6 @@
---
id: overview
title: Overview
ref: docs/framework/react/overview.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,5 @@
---
id: broadcastQueryClient
title: broadcastQueryClient (Experimental)
ref: docs/framework/react/plugins/broadcastQueryClient.md
---

View File

@@ -0,0 +1,6 @@
---
id: createAsyncStoragePersister
title: createAsyncStoragePersister
ref: docs/framework/react/plugins/createAsyncStoragePersister.md
replace: { 'react-query': 'preact-query' }
---

View File

@@ -0,0 +1,6 @@
---
id: createPersister
title: experimental_createPersister
ref: docs/framework/react/plugins/createPersister.md
replace: { 'react-query': 'preact-query' }
---

View File

@@ -0,0 +1,6 @@
---
id: createSyncStoragePersister
title: createSyncStoragePersister
ref: docs/framework/react/plugins/createSyncStoragePersister.md
replace: { 'react-query': 'preact-query' }
---

View File

@@ -0,0 +1,6 @@
---
id: persistQueryClient
title: persistQueryClient
ref: docs/framework/react/plugins/persistQueryClient.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,6 @@
---
id: quick-start
title: Quick Start
ref: docs/framework/react/quick-start.md
replace: { 'react-query': 'preact-query', 'React': 'Preact' }
---

View File

@@ -0,0 +1,273 @@
---
id: CancelledError
title: CancelledError
---
Defined in: [packages/query-core/src/retryer.ts:77](https://github.com/TanStack/query/blob/main/packages/query-core/src/retryer.ts#L77)
The error thrown by a `Retryer` (and surfaced to `query.promise`/`mutation`) when a fetch is cancelled, e.g. via
`query.cancel()`. `revert`, if `true`, tells the caller to restore the state the query was in before the fetch
started instead of surfacing the error. `silent`, if `true`, tells the caller to suppress this error and instead
resolve with the promise of the fetch that triggered the cancellation.
## Example
```ts
query.cancel()
try {
await query.promise
} catch (error) {
if (error instanceof CancelledError) {
// the fetch was cancelled, e.g. via `query.cancel()`
}
}
```
## Extends
- `Error`
## Constructors
### Constructor
```ts
new CancelledError(options?): CancelledError;
```
Defined in: [packages/query-core/src/retryer.ts:80](https://github.com/TanStack/query/blob/main/packages/query-core/src/retryer.ts#L80)
#### Parameters
##### options?
[`CancelOptions`](../interfaces/CancelOptions.md)
#### Returns
`CancelledError`
#### Overrides
```ts
Error.constructor
```
## Properties
### cause?
```ts
optional cause: unknown;
```
Defined in: node\_modules/.pnpm/typescript@6.0.3/node\_modules/typescript/lib/lib.es2022.error.d.ts:24
#### Inherited from
```ts
Error.cause
```
***
### message
```ts
message: string;
```
Defined in: node\_modules/.pnpm/typescript@6.0.3/node\_modules/typescript/lib/lib.es5.d.ts:1075
#### Inherited from
```ts
Error.message
```
***
### name
```ts
name: string;
```
Defined in: node\_modules/.pnpm/typescript@6.0.3/node\_modules/typescript/lib/lib.es5.d.ts:1074
#### Inherited from
```ts
Error.name
```
***
### revert?
```ts
optional revert: boolean;
```
Defined in: [packages/query-core/src/retryer.ts:78](https://github.com/TanStack/query/blob/main/packages/query-core/src/retryer.ts#L78)
***
### silent?
```ts
optional silent: boolean;
```
Defined in: [packages/query-core/src/retryer.ts:79](https://github.com/TanStack/query/blob/main/packages/query-core/src/retryer.ts#L79)
***
### stack?
```ts
optional stack: string;
```
Defined in: node\_modules/.pnpm/typescript@6.0.3/node\_modules/typescript/lib/lib.es5.d.ts:1076
#### Inherited from
```ts
Error.stack
```
***
### stackTraceLimit
```ts
static stackTraceLimit: number;
```
Defined in: node\_modules/.pnpm/@types+node@22.19.15/node\_modules/@types/node/globals.d.ts:68
The `Error.stackTraceLimit` property specifies the number of stack frames
collected by a stack trace (whether generated by `new Error().stack` or
`Error.captureStackTrace(obj)`).
The default value is `10` but may be set to any valid JavaScript number. Changes
will affect any stack trace captured _after_ the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will
not capture any frames.
#### Inherited from
```ts
Error.stackTraceLimit
```
## Methods
### captureStackTrace()
```ts
static captureStackTrace(targetObject, constructorOpt?): void;
```
Defined in: node\_modules/.pnpm/@types+node@22.19.15/node\_modules/@types/node/globals.d.ts:52
Creates a `.stack` property on `targetObject`, which when accessed returns
a string representing the location in the code at which
`Error.captureStackTrace()` was called.
```js
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
```
The first line of the trace will be prefixed with
`${myObject.name}: ${myObject.message}`.
The optional `constructorOpt` argument accepts a function. If given, all frames
above `constructorOpt`, including `constructorOpt`, will be omitted from the
generated stack trace.
The `constructorOpt` argument is useful for hiding implementation
details of error generation from the user. For instance:
```js
function a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();
```
#### Parameters
##### targetObject
`object`
##### constructorOpt?
`Function`
#### Returns
`void`
#### Inherited from
```ts
Error.captureStackTrace
```
***
### prepareStackTrace()
```ts
static prepareStackTrace(err, stackTraces): any;
```
Defined in: node\_modules/.pnpm/@types+node@22.19.15/node\_modules/@types/node/globals.d.ts:56
#### Parameters
##### err
`Error`
##### stackTraces
`CallSite`[]
#### Returns
`any`
#### See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
#### Inherited from
```ts
Error.prepareStackTrace
```

View File

@@ -0,0 +1,665 @@
---
id: InfiniteQueryObserver
title: InfiniteQueryObserver
---
Defined in: [packages/query-core/src/infiniteQueryObserver.ts:41](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L41)
An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch
between infinite queries. It augments the base `QueryObserverResult` with
infinite-query-specific fields and methods, such as `hasNextPage` and
`fetchNextPage`, and is the primitive that framework adapters (e.g.
`useInfiniteQuery`) build their hooks on top of.
## Example
```ts
const observer = new InfiniteQueryObserver(queryClient, {
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextCursor,
})
const unsubscribe = observer.subscribe((result) => console.log(result))
```
## Extends
- [`QueryObserver`](QueryObserver.md)\<`TQueryFnData`, `TError`, `TData`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>
## Type Parameters
### TQueryFnData
`TQueryFnData` = `unknown`
### TError
`TError` = [`DefaultError`](../type-aliases/DefaultError.md)
### TData
`TData` = [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`\>
### TQueryKey
`TQueryKey` *extends* [`QueryKey`](../type-aliases/QueryKey.md) = [`QueryKey`](../type-aliases/QueryKey.md)
### TPageParam
`TPageParam` = `unknown`
## Constructors
### Constructor
```ts
new InfiniteQueryObserver<TQueryFnData, TError, TData, TQueryKey, TPageParam>(client, options): InfiniteQueryObserver<TQueryFnData, TError, TData, TQueryKey, TPageParam>;
```
Defined in: [packages/query-core/src/infiniteQueryObserver.ts:83](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L83)
#### Parameters
##### client
[`QueryClient`](QueryClient.md)
##### options
[`InfiniteQueryObserverOptions`](../interfaces/InfiniteQueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
#### Returns
`InfiniteQueryObserver`\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
#### Overrides
[`QueryObserver`](QueryObserver.md).[`constructor`](QueryObserver.md#constructor)
## Properties
### fetch
```ts
protected fetch: ReplaceReturnType<(fetchOptions) => Promise<QueryObserverResult<TData, TError>>, Promise<InfiniteQueryObserverResult<TData, TError>>>;
```
Defined in: [packages/query-core/src/infiniteQueryObserver.ts:72](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L72)
#### Overrides
```ts
QueryObserver.fetch
```
***
### getCurrentResult
```ts
getCurrentResult: ReplaceReturnType<() => QueryObserverResult<TData, TError>, InfiniteQueryObserverResult<TData, TError>>;
```
Defined in: [packages/query-core/src/infiniteQueryObserver.ts:60](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L60)
Returns the most recently computed `QueryObserverResult` for the
observed query. This is a point-in-time read; to be notified of updates
as they happen, subscribe to the observer instead (its inherited
`subscribe` method).
#### Example
```ts
const result = observer.getCurrentResult()
console.log(result.status, result.data)
```
#### Overrides
```ts
QueryObserver.getCurrentResult
```
***
### listeners
```ts
protected listeners: Set<QueryObserverListener<TData, TError>>;
```
Defined in: [packages/query-core/src/subscribable.ts:2](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L2)
#### Inherited from
[`QueryObserver`](QueryObserver.md).[`listeners`](QueryObserver.md#listeners)
***
### options
```ts
options: QueryObserverOptions<TQueryFnData, TError, TData, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>;
```
Defined in: [packages/query-core/src/queryObserver.ts:89](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L89)
#### Inherited from
[`QueryObserver`](QueryObserver.md).[`options`](QueryObserver.md#options)
***
### subscribe()
```ts
subscribe: (listener) => () => void;
```
Defined in: [packages/query-core/src/infiniteQueryObserver.ts:55](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L55)
#### Parameters
##### listener
`InfiniteQueryObserverListener`
#### Returns
```ts
(): void;
```
##### Returns
`void`
#### Overrides
```ts
QueryObserver.subscribe
```
## Methods
### bindMethods()
```ts
protected bindMethods(): void;
```
Defined in: [packages/query-core/src/infiniteQueryObserver.ts:96](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L96)
#### Returns
`void`
#### Overrides
[`QueryObserver`](QueryObserver.md).[`bindMethods`](QueryObserver.md#bindmethods)
***
### createResult()
```ts
protected createResult(query, options): InfiniteQueryObserverResult<TData, TError>;
```
Defined in: [packages/query-core/src/infiniteQueryObserver.ts:201](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L201)
#### Parameters
##### query
[`Query`](Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>
##### options
[`InfiniteQueryObserverOptions`](../interfaces/InfiniteQueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
#### Returns
[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>
#### Overrides
[`QueryObserver`](QueryObserver.md).[`createResult`](QueryObserver.md#createresult)
***
### destroy()
```ts
destroy(): void;
```
Defined in: [packages/query-core/src/queryObserver.ts:161](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L161)
Stops observing the current query: clears all listeners, cancels the
stale and refetch-interval timers, and removes this observer from the
query it was observing.
#### Returns
`void`
#### Inherited from
[`QueryObserver`](QueryObserver.md).[`destroy`](QueryObserver.md#destroy)
***
### fetchNextPage()
```ts
fetchNextPage(options?): Promise<InfiniteQueryObserverResult<TData, TError>>;
```
Defined in: [packages/query-core/src/infiniteQueryObserver.ts:161](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L161)
Fetches the next page of the infinite query and returns a promise that
resolves with the resulting `InfiniteQueryObserverResult`. The page
param used for the fetch is determined by `getNextPageParam`, which
receives the current pages/page params and whose result also determines
`hasNextPage`.
#### Parameters
##### options?
[`FetchNextPageOptions`](../interfaces/FetchNextPageOptions.md)
#### Returns
`Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\>
#### Example
```ts
const { hasNextPage } = observer.getCurrentResult()
if (hasNextPage) {
await observer.fetchNextPage()
}
```
#### See
[InfiniteQueryObserver#fetchPreviousPage](#fetchpreviouspage)
***
### fetchOptimistic()
```ts
fetchOptimistic(options): Promise<QueryObserverResult<TData, TError>>;
```
Defined in: [packages/query-core/src/queryObserver.ts:395](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L395)
Fetches a query defined by the given options without affecting this
observer's own tracked query or result, and returns a promise that
resolves with the `QueryObserverResult` for that fetch. This is useful
for prefetching data that another observer (e.g. a query about to be
navigated to) will need, ahead of time.
#### Parameters
##### options
[`QueryObserverOptions`](../interfaces/QueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>
#### Returns
`Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\>
#### Example
```ts
const result = await observer.fetchOptimistic({
queryKey: ['posts', 2],
queryFn: () => fetchPost(2),
})
console.log(result.data)
```
#### Inherited from
[`QueryObserver`](QueryObserver.md).[`fetchOptimistic`](QueryObserver.md#fetchoptimistic)
***
### fetchPreviousPage()
```ts
fetchPreviousPage(options?): Promise<InfiniteQueryObserverResult<TData, TError>>;
```
Defined in: [packages/query-core/src/infiniteQueryObserver.ts:190](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L190)
Fetches the previous page of the infinite query and returns a promise
that resolves with the resulting `InfiniteQueryObserverResult`. The page
param used for the fetch is determined by `getPreviousPageParam`, which
receives the current pages/page params and whose result also determines
`hasPreviousPage`.
#### Parameters
##### options?
[`FetchPreviousPageOptions`](../interfaces/FetchPreviousPageOptions.md)
#### Returns
`Promise`\<[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>\>
#### Example
```ts
const { hasPreviousPage } = observer.getCurrentResult()
if (hasPreviousPage) {
await observer.fetchPreviousPage()
}
```
#### See
[InfiniteQueryObserver#fetchNextPage](#fetchnextpage)
***
### getCurrentQuery()
```ts
getCurrentQuery(): Query<TQueryFnData, TError, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>;
```
Defined in: [packages/query-core/src/queryObserver.ts:357](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L357)
Returns the `Query` instance this observer is currently observing.
#### Returns
[`Query`](Query.md)\<`TQueryFnData`, `TError`, [`InfiniteData`](../interfaces/InfiniteData.md)\<`TQueryFnData`, `TPageParam`\>, `TQueryKey`\>
#### Inherited from
[`QueryObserver`](QueryObserver.md).[`getCurrentQuery`](QueryObserver.md#getcurrentquery)
***
### getOptimisticResult()
```ts
getOptimisticResult(options): InfiniteQueryObserverResult<TData, TError>;
```
Defined in: [packages/query-core/src/infiniteQueryObserver.ts:127](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L127)
The infinite-query counterpart of [QueryObserver#getOptimisticResult](QueryObserver.md#getoptimisticresult), marking the
options as an infinite query before delegating to it. Called by framework adapters (e.g.
`useInfiniteQuery`) ahead of subscribing, to compute the current `InfiniteQueryObserverResult`
synchronously.
#### Parameters
##### options
[`DefaultedInfiniteQueryObserverOptions`](../type-aliases/DefaultedInfiniteQueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
#### Returns
[`InfiniteQueryObserverResult`](../type-aliases/InfiniteQueryObserverResult.md)\<`TData`, `TError`\>
#### Overrides
[`QueryObserver`](QueryObserver.md).[`getOptimisticResult`](QueryObserver.md#getoptimisticresult)
***
### hasListeners()
```ts
hasListeners(): boolean;
```
Defined in: [packages/query-core/src/subscribable.ts:19](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L19)
#### Returns
`boolean`
#### Inherited from
[`QueryObserver`](QueryObserver.md).[`hasListeners`](QueryObserver.md#haslisteners)
***
### onSubscribe()
```ts
protected onSubscribe(): void;
```
Defined in: [packages/query-core/src/queryObserver.ts:110](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L110)
#### Returns
`void`
#### Inherited from
[`QueryObserver`](QueryObserver.md).[`onSubscribe`](QueryObserver.md#onsubscribe)
***
### onUnsubscribe()
```ts
protected onUnsubscribe(): void;
```
Defined in: [packages/query-core/src/queryObserver.ts:124](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L124)
#### Returns
`void`
#### Inherited from
[`QueryObserver`](QueryObserver.md).[`onUnsubscribe`](QueryObserver.md#onunsubscribe)
***
### refetch()
```ts
refetch(__namedParameters): Promise<QueryObserverResult<TData, TError>>;
```
Defined in: [packages/query-core/src/queryObserver.ts:371](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L371)
Refetches the observed query and returns a promise that resolves with
the resulting `QueryObserverResult`.
#### Parameters
##### \_\_namedParameters
[`RefetchOptions`](../interfaces/RefetchOptions.md) = `{}`
#### Returns
`Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\>
#### Example
```ts
const result = await observer.refetch({ cancelRefetch: false })
console.log(result.data)
```
#### Inherited from
[`QueryObserver`](QueryObserver.md).[`refetch`](QueryObserver.md#refetch)
***
### setOptions()
```ts
setOptions(options): void;
```
Defined in: [packages/query-core/src/infiniteQueryObserver.ts:108](https://github.com/TanStack/query/blob/main/packages/query-core/src/infiniteQueryObserver.ts#L108)
Updates the observer's options. Behaves the same as
`QueryObserver.setOptions`, additionally marking the options as
belonging to an infinite query before delegating to the base
implementation.
#### Parameters
##### options
[`InfiniteQueryObserverOptions`](../interfaces/InfiniteQueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
#### Returns
`void`
#### Overrides
[`QueryObserver`](QueryObserver.md).[`setOptions`](QueryObserver.md#setoptions)
***
### shouldFetchOnReconnect()
```ts
shouldFetchOnReconnect(): boolean;
```
Defined in: [packages/query-core/src/queryObserver.ts:135](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L135)
Returns whether the observed query is currently stale and configured
(via the `refetchOnReconnect` option) to refetch when the network
reconnects.
#### Returns
`boolean`
#### Inherited from
[`QueryObserver`](QueryObserver.md).[`shouldFetchOnReconnect`](QueryObserver.md#shouldfetchonreconnect)
***
### shouldFetchOnWindowFocus()
```ts
shouldFetchOnWindowFocus(): boolean;
```
Defined in: [packages/query-core/src/queryObserver.ts:148](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L148)
Returns whether the observed query is currently stale and configured
(via the `refetchOnWindowFocus` option) to refetch when the window
regains focus.
#### Returns
`boolean`
#### Inherited from
[`QueryObserver`](QueryObserver.md).[`shouldFetchOnWindowFocus`](QueryObserver.md#shouldfetchonwindowfocus)
***
### trackProp()
```ts
trackProp(key): void;
```
Defined in: [packages/query-core/src/queryObserver.ts:350](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L350)
Records that the given `QueryObserverResult` property was read, so a subsequent update only
notifies this observer if a tracked property actually changed. Normally called indirectly via
[QueryObserver#trackResult](QueryObserver.md#trackresult)'s proxy; exposed directly for adapters that track property
access themselves (e.g. through their own reactivity system) instead of via the proxy.
#### Parameters
##### key
`"error"` | `"data"` | `"isError"` | `"isPending"` | `"isLoading"` | `"isLoadingError"` | `"isRefetchError"` | `"isSuccess"` | `"isPlaceholderData"` | `"status"` | `"dataUpdatedAt"` | `"errorUpdatedAt"` | `"failureCount"` | `"failureReason"` | `"errorUpdateCount"` | `"isFetched"` | `"isFetchedAfterMount"` | `"isFetching"` | `"isInitialLoading"` | `"isPaused"` | `"isRefetching"` | `"isStale"` | `"isEnabled"` | `"refetch"` | `"fetchStatus"`
#### Returns
`void`
#### Inherited from
[`QueryObserver`](QueryObserver.md).[`trackProp`](QueryObserver.md#trackprop)
***
### trackResult()
```ts
trackResult(result, onPropTracked?): QueryObserverResult<TData, TError>;
```
Defined in: [packages/query-core/src/queryObserver.ts:331](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L331)
Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via
[QueryObserver#trackProp](QueryObserver.md#trackprop) (and an optional `onPropTracked` callback). Used by framework
adapters when `notifyOnChangeProps` is not set, to implement its default "only re-render on
properties you actually read" behavior.
#### Parameters
##### result
[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
##### onPropTracked?
(`key`) => `void`
#### Returns
[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
#### Inherited from
[`QueryObserver`](QueryObserver.md).[`trackResult`](QueryObserver.md#trackresult)
***
### updateResult()
```ts
updateResult(): void;
```
Defined in: [packages/query-core/src/queryObserver.ts:735](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L735)
Recomputes and stores the current result from the current query/options, notifying listeners
if it changed. Framework adapters call this right after subscribing to make sure no query
update was missed in the gap between creating the observer and subscribing to it.
#### Returns
`void`
#### Inherited from
[`QueryObserver`](QueryObserver.md).[`updateResult`](QueryObserver.md#updateresult)

View File

@@ -0,0 +1,330 @@
---
id: Mutation
title: Mutation
---
Defined in: [packages/query-core/src/mutation.ts:135](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutation.ts#L135)
Represents a single mutation attempt. A `Mutation` holds the mutation's
options, state (data/error/status), and the `MutationObserver`s currently
subscribed to it.
Instances are created and managed internally by `MutationCache`; application
code typically interacts with mutations indirectly through `QueryClient` or
a framework hook like `useMutation`. Direct access to a `Mutation` instance
is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.
## Example
```ts
const mutationCache = queryClient.getMutationCache()
const mutation = mutationCache.find({ mutationKey: ['addPost'] })
```
## Extends
- `Removable`
## Type Parameters
### TData
`TData` = `unknown`
### TError
`TError` = [`DefaultError`](../type-aliases/DefaultError.md)
### TVariables
`TVariables` = `unknown`
### TOnMutateResult
`TOnMutateResult` = `unknown`
## Constructors
### Constructor
```ts
new Mutation<TData, TError, TVariables, TOnMutateResult>(config): Mutation<TData, TError, TVariables, TOnMutateResult>;
```
Defined in: [packages/query-core/src/mutation.ts:152](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutation.ts#L152)
#### Parameters
##### config
`MutationConfig`\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
#### Returns
`Mutation`\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
#### Overrides
```ts
Removable.constructor
```
## Properties
### gcTime
```ts
gcTime: number;
```
Defined in: [packages/query-core/src/removable.ts:7](https://github.com/TanStack/query/blob/main/packages/query-core/src/removable.ts#L7)
#### Inherited from
```ts
Removable.gcTime
```
***
### mutationId
```ts
readonly mutationId: number;
```
Defined in: [packages/query-core/src/mutation.ts:143](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutation.ts#L143)
***
### options
```ts
options: MutationOptions<TData, TError, TVariables, TOnMutateResult>;
```
Defined in: [packages/query-core/src/mutation.ts:142](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutation.ts#L142)
***
### state
```ts
state: MutationState<TData, TError, TVariables, TOnMutateResult>;
```
Defined in: [packages/query-core/src/mutation.ts:141](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutation.ts#L141)
## Accessors
### meta
#### Get Signature
```ts
get meta(): Record<string, unknown> | undefined;
```
Defined in: [packages/query-core/src/mutation.ts:179](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutation.ts#L179)
The `meta` object passed in the mutation's options, if any.
##### Returns
`Record`\<`string`, `unknown`\> \| `undefined`
## Methods
### clearGcTimeout()
```ts
protected clearGcTimeout(): void;
```
Defined in: [packages/query-core/src/removable.ts:32](https://github.com/TanStack/query/blob/main/packages/query-core/src/removable.ts#L32)
#### Returns
`void`
#### Inherited from
```ts
Removable.clearGcTimeout
```
***
### continue()
```ts
continue(): Promise<unknown>;
```
Defined in: [packages/query-core/src/mutation.ts:243](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutation.ts#L243)
Resumes a mutation that is currently paused or was restored from a
dehydrated, still-`pending` state.
- If this mutation has an active retryer (it paused mid-attempt, e.g. due
to the network mode or scope-based queuing), its retryer is resumed.
- Otherwise, if the mutation's status is still `pending` (e.g. it was
dehydrated while an attempt was in flight and never got a retryer in
this instance), `execute` is called again with the last known variables.
- Otherwise the mutation has already settled and this resolves immediately
without running anything again.
#### Returns
`Promise`\<`unknown`\>
#### Example
```ts
// typically driven by reconnect handling, e.g. queryClient.resumePausedMutations()
const mutation = mutationCache.find({ mutationKey: ['addPost'] })
await mutation?.continue()
```
#### See
[Mutation#execute](#execute)
***
### destroy()
```ts
destroy(): void;
```
Defined in: [packages/query-core/src/removable.ts:10](https://github.com/TanStack/query/blob/main/packages/query-core/src/removable.ts#L10)
#### Returns
`void`
#### Inherited from
```ts
Removable.destroy
```
***
### execute()
```ts
execute(variables): Promise<TData>;
```
Defined in: [packages/query-core/src/mutation.ts:284](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutation.ts#L284)
Runs the mutation function for the given variables through a retryer, and
drives the mutation's state and lifecycle callbacks through to settlement.
If this mutation's state is already `pending` when `execute` is called
(i.e. it was restored, still in-flight, from a dehydrated state), the
`onMutate` step is skipped and a `continue` action is dispatched to
unpause it; otherwise a `pending` action is dispatched first, then the
mutation cache's `onMutate` and the mutation's own `onMutate` option are
awaited in that order, and the resulting context is stored.
The mutation function is then run (subject to `retry`/`retryDelay`/
`networkMode`, and to the mutation cache's scope-based serialization).
On success, the cache's `onSuccess`/`onSettled` callbacks run before the
mutation's own `onSuccess`/`onSettled` options, a `success` action is
dispatched, and the resolved data is returned. On failure, the same
cache-then-option ordering is used for `onError`/`onSettled`, but each of
those four callbacks is individually caught so that a throwing callback
cannot mask the original error; an `error` action is then dispatched and
the original error is re-thrown.
#### Parameters
##### variables
`TVariables`
#### Returns
`Promise`\<`TData`\>
#### Example
```ts
// Called internally by `MutationObserver.mutate` and `Mutation.continue` —
// applications normally trigger mutations through those, not this method.
const data = await mutation.execute(variables)
```
#### See
[Mutation#continue](#continue)
***
### optionalRemove()
```ts
protected optionalRemove(): void;
```
Defined in: [packages/query-core/src/mutation.ts:212](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutation.ts#L212)
#### Returns
`void`
#### Overrides
```ts
Removable.optionalRemove
```
***
### scheduleGc()
```ts
protected scheduleGc(): void;
```
Defined in: [packages/query-core/src/removable.ts:14](https://github.com/TanStack/query/blob/main/packages/query-core/src/removable.ts#L14)
#### Returns
`void`
#### Inherited from
```ts
Removable.scheduleGc
```
***
### updateGcTime()
```ts
protected updateGcTime(newGcTime): void;
```
Defined in: [packages/query-core/src/removable.ts:24](https://github.com/TanStack/query/blob/main/packages/query-core/src/removable.ts#L24)
#### Parameters
##### newGcTime
`number` | `undefined`
#### Returns
`void`
#### Inherited from
```ts
Removable.updateGcTime
```

View File

@@ -0,0 +1,316 @@
---
id: MutationCache
title: MutationCache
---
Defined in: [packages/query-core/src/mutationCache.ts:124](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationCache.ts#L124)
The `MutationCache` is the storage for mutations.
Normally, you will not interact with the `MutationCache` directly and instead use a
`QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of
safe/known updates to the cache, such as mutations being added, removed, or updated.
## Example
```ts
const unsubscribe = mutationCache.subscribe((event) => {
console.log(event.type, event.mutation)
})
```
## Extends
- `Subscribable`\<`MutationCacheListener`\>
## Constructors
### Constructor
```ts
new MutationCache(config): MutationCache;
```
Defined in: [packages/query-core/src/mutationCache.ts:129](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationCache.ts#L129)
#### Parameters
##### config
[`MutationCacheConfig`](../interfaces/MutationCacheConfig.md) = `{}`
#### Returns
`MutationCache`
#### Overrides
```ts
Subscribable<MutationCacheListener>.constructor
```
## Properties
### config
```ts
config: MutationCacheConfig = {};
```
Defined in: [packages/query-core/src/mutationCache.ts:129](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationCache.ts#L129)
***
### listeners
```ts
protected listeners: Set<MutationCacheListener>;
```
Defined in: [packages/query-core/src/subscribable.ts:2](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L2)
#### Inherited from
```ts
Subscribable.listeners
```
## Methods
### clear()
```ts
clear(): void;
```
Defined in: [packages/query-core/src/mutationCache.ts:236](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationCache.ts#L236)
Removes all mutations from the cache.
#### Returns
`void`
#### Example
```ts
const mutationCache = queryClient.getMutationCache()
mutationCache.clear()
```
***
### find()
```ts
find<TData, TError, TVariables, TOnMutateResult>(filters):
| Mutation<TData, TError, TVariables, TOnMutateResult>
| undefined;
```
Defined in: [packages/query-core/src/mutationCache.ts:278](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationCache.ts#L278)
A slightly more advanced method that can be used to get an existing mutation instance from
the cache. If the mutation does not exist, `undefined` is returned.
This is not typically needed for most applications, but can come in handy when needing more
information about a mutation in rare scenarios.
#### Type Parameters
##### TData
`TData` = `unknown`
##### TError
`TError` = `Error`
##### TVariables
`TVariables` = `any`
##### TOnMutateResult
`TOnMutateResult` = `unknown`
#### Parameters
##### filters
[`MutationFilters`](../interfaces/MutationFilters.md)
#### Returns
\| [`Mutation`](Mutation.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
\| `undefined`
#### See
[MutationCache#findAll](#findall)
#### Example
```ts
const mutationCache = queryClient.getMutationCache()
const mutation = mutationCache.find({ mutationKey: ['addPost'] })
```
***
### findAll()
```ts
findAll(filters): Mutation<unknown, Error, unknown, unknown>[];
```
Defined in: [packages/query-core/src/mutationCache.ts:308](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationCache.ts#L308)
An even more advanced method that can be used to get existing mutation instances from the
cache that match the given filters. If no mutations match, an empty array is returned.
This is not typically needed for most applications, but can come in handy when needing more
information about mutations in rare scenarios.
#### Parameters
##### filters
[`MutationFilters`](../interfaces/MutationFilters.md) = `{}`
#### Returns
[`Mutation`](Mutation.md)\<`unknown`, `Error`, `unknown`, `unknown`\>[]
#### See
[MutationCache#find](#find)
#### Example
```ts
const mutationCache = queryClient.getMutationCache()
const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })
```
***
### getAll()
```ts
getAll(): Mutation<unknown, Error, unknown, unknown>[];
```
Defined in: [packages/query-core/src/mutationCache.ts:259](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationCache.ts#L259)
Returns all mutations within the cache.
This is not typically needed for most applications, but can come in handy when needing more
information about a mutation in rare scenarios.
#### Returns
[`Mutation`](Mutation.md)\<`unknown`, `Error`, `unknown`, `unknown`\>[]
#### Example
```ts
const mutationCache = queryClient.getMutationCache()
const mutations = mutationCache.getAll()
```
***
### hasListeners()
```ts
hasListeners(): boolean;
```
Defined in: [packages/query-core/src/subscribable.ts:19](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L19)
#### Returns
`boolean`
#### Inherited from
```ts
Subscribable.hasListeners
```
***
### onSubscribe()
```ts
protected onSubscribe(): void;
```
Defined in: [packages/query-core/src/subscribable.ts:23](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L23)
#### Returns
`void`
#### Inherited from
```ts
Subscribable.onSubscribe
```
***
### onUnsubscribe()
```ts
protected onUnsubscribe(): void;
```
Defined in: [packages/query-core/src/subscribable.ts:27](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L27)
#### Returns
`void`
#### Inherited from
```ts
Subscribable.onUnsubscribe
```
***
### subscribe()
```ts
subscribe(listener): () => void;
```
Defined in: [packages/query-core/src/subscribable.ts:8](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L8)
#### Parameters
##### listener
`MutationCacheListener`
#### Returns
```ts
(): void;
```
##### Returns
`void`
#### Inherited from
```ts
Subscribable.subscribe
```

View File

@@ -0,0 +1,335 @@
---
id: MutationObserver
title: MutationObserver
---
Defined in: [packages/query-core/src/mutationObserver.ts:38](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationObserver.ts#L38)
Observes a single mutation and derives a `MutationObserverResult` from it.
A framework hook like `useMutation` creates one `MutationObserver` per hook
call, keeps it stable across re-renders, calls `setOptions` when the options
passed to the hook change, subscribes to it to re-render on updates, and
reads `getCurrentResult()` for the value to return. Calling `mutate()`
builds a new underlying `Mutation` in the `MutationCache` and executes it.
## Example
```ts
const observer = new MutationObserver(queryClient, {
mutationFn: (variables: { title: string }) => addPost(variables),
})
```
## Extends
- `Subscribable`\<`MutationObserverListener`\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>\>
## Type Parameters
### TData
`TData` = `unknown`
### TError
`TError` = [`DefaultError`](../type-aliases/DefaultError.md)
### TVariables
`TVariables` = `void`
### TOnMutateResult
`TOnMutateResult` = `unknown`
## Constructors
### Constructor
```ts
new MutationObserver<TData, TError, TVariables, TOnMutateResult>(client, options): MutationObserver<TData, TError, TVariables, TOnMutateResult>;
```
Defined in: [packages/query-core/src/mutationObserver.ts:58](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationObserver.ts#L58)
#### Parameters
##### client
[`QueryClient`](QueryClient.md)
##### options
[`MutationObserverOptions`](../interfaces/MutationObserverOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
#### Returns
`MutationObserver`\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
#### Overrides
```ts
Subscribable<
MutationObserverListener<TData, TError, TVariables, TOnMutateResult>
>.constructor
```
## Properties
### listeners
```ts
protected listeners: Set<MutationObserverListener<TData, TError, TVariables, TOnMutateResult>>;
```
Defined in: [packages/query-core/src/subscribable.ts:2](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L2)
#### Inherited from
```ts
Subscribable.listeners
```
***
### options
```ts
options: MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>;
```
Defined in: [packages/query-core/src/mutationObserver.ts:46](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationObserver.ts#L46)
## Methods
### bindMethods()
```ts
protected bindMethods(): void;
```
Defined in: [packages/query-core/src/mutationObserver.ts:75](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationObserver.ts#L75)
#### Returns
`void`
***
### getCurrentResult()
```ts
getCurrentResult(): MutationObserverResult<TData, TError, TVariables, TOnMutateResult>;
```
Defined in: [packages/query-core/src/mutationObserver.ts:155](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationObserver.ts#L155)
Returns the observer's current result, derived from the observed
mutation's state (or the default, `idle` state if no mutation has been
built yet, e.g. before the first `mutate()` call or after `reset()`).
#### Returns
[`MutationObserverResult`](../type-aliases/MutationObserverResult.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
***
### hasListeners()
```ts
hasListeners(): boolean;
```
Defined in: [packages/query-core/src/subscribable.ts:19](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L19)
#### Returns
`boolean`
#### Inherited from
```ts
Subscribable.hasListeners
```
***
### mutate()
```ts
mutate(variables, options?): Promise<TData>;
```
Defined in: [packages/query-core/src/mutationObserver.ts:207](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationObserver.ts#L207)
Builds a new `Mutation` in the `MutationCache` using the observer's
current options, detaches this observer from any previously observed
mutation, attaches it to the new one, and executes it with the given
variables.
The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are
invoked once the mutation settles, in addition to any callbacks defined
on the observer's own options.
#### Parameters
##### variables
`TVariables`
##### options?
[`MutateOptions`](../interfaces/MutateOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
#### Returns
`Promise`\<`TData`\>
#### Example
```ts
await observer.mutate(
{ title: 'New post' },
{ onSuccess: (data) => console.log(data) },
)
```
***
### onSubscribe()
```ts
protected onSubscribe(): void;
```
Defined in: [packages/query-core/src/mutationObserver.ts:127](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationObserver.ts#L127)
#### Returns
`void`
#### Overrides
```ts
Subscribable.onSubscribe
```
***
### onUnsubscribe()
```ts
protected onUnsubscribe(): void;
```
Defined in: [packages/query-core/src/mutationObserver.ts:135](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationObserver.ts#L135)
#### Returns
`void`
#### Overrides
```ts
Subscribable.onUnsubscribe
```
***
### reset()
```ts
reset(): void;
```
Defined in: [packages/query-core/src/mutationObserver.ts:180](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationObserver.ts#L180)
Detaches the observer from the mutation it is currently observing (if
any) and resets the observed result back to its default, `idle` state.
This does not cancel an in-flight mutation; the mutation itself keeps
running to completion and its own callbacks still fire, but this
observer stops reflecting its state and a subsequent `mutate()` call
will build a brand new mutation.
#### Returns
`void`
#### Example
```ts
observer.reset()
```
#### See
[MutationObserver#mutate](#mutate)
***
### setOptions()
```ts
setOptions(options): void;
```
Defined in: [packages/query-core/src/mutationObserver.ts:96](https://github.com/TanStack/query/blob/main/packages/query-core/src/mutationObserver.ts#L96)
Updates the observer's options.
If the new `mutationKey` differs from the previous one (and both were
defined), the observer is reset, detaching it from the mutation it was
observing. Otherwise, if the currently observed mutation is still
`pending`, its options are updated in place as well.
#### Parameters
##### options
[`MutationObserverOptions`](../interfaces/MutationObserverOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
#### Returns
`void`
#### Example
```ts
observer.setOptions({
mutationFn: (variables: { title: string }) => addPost(variables),
onSuccess: (data) => console.log(data),
})
```
***
### subscribe()
```ts
subscribe(listener): () => void;
```
Defined in: [packages/query-core/src/subscribable.ts:8](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L8)
#### Parameters
##### listener
`MutationObserverListener`
#### Returns
```ts
(): void;
```
##### Returns
`void`
#### Inherited from
```ts
Subscribable.subscribe
```

View File

@@ -0,0 +1,325 @@
---
id: QueriesObserver
title: QueriesObserver
---
Defined in: [packages/query-core/src/queriesObserver.ts:56](https://github.com/TanStack/query/blob/main/packages/query-core/src/queriesObserver.ts#L56)
A `QueriesObserver` watches an array of queries at once, exposing them as
a single array of `QueryObserverResult`s (or, when a `combine` option is
given, as a combined value derived from that array). It manages one
internal `QueryObserver` per query, and is the primitive that framework
adapters (e.g. `useQueries`) build their hooks on top of.
## Example
```ts
const observer = new QueriesObserver(queryClient, [
{ queryKey: ['post', 1], queryFn: fetchPost },
{ queryKey: ['post', 2], queryFn: fetchPost },
])
const unsubscribe = observer.subscribe((result) => {
console.log(result)
})
```
## Extends
- `Subscribable`\<`QueriesObserverListener`\>
## Type Parameters
### TCombinedResult
`TCombinedResult` = [`QueryObserverResult`](../type-aliases/QueryObserverResult.md)[]
## Constructors
### Constructor
```ts
new QueriesObserver<TCombinedResult>(
client,
queries,
options?): QueriesObserver<TCombinedResult>;
```
Defined in: [packages/query-core/src/queriesObserver.ts:70](https://github.com/TanStack/query/blob/main/packages/query-core/src/queriesObserver.ts#L70)
#### Parameters
##### client
[`QueryClient`](QueryClient.md)
##### queries
[`QueryObserverOptions`](../interfaces/QueryObserverOptions.md)\<`any`, `any`, `any`, `any`, `any`, `never`\>[]
##### options?
[`QueriesObserverOptions`](../interfaces/QueriesObserverOptions.md)\<`TCombinedResult`\>
#### Returns
`QueriesObserver`\<`TCombinedResult`\>
#### Overrides
```ts
Subscribable<QueriesObserverListener>.constructor
```
## Properties
### listeners
```ts
protected listeners: Set<QueriesObserverListener>;
```
Defined in: [packages/query-core/src/subscribable.ts:2](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L2)
#### Inherited from
```ts
Subscribable.listeners
```
## Methods
### destroy()
```ts
destroy(): void;
```
Defined in: [packages/query-core/src/queriesObserver.ts:106](https://github.com/TanStack/query/blob/main/packages/query-core/src/queriesObserver.ts#L106)
Stops observing all queries: clears all listeners and destroys every
underlying `QueryObserver` this observer manages.
#### Returns
`void`
***
### getCurrentResult()
```ts
getCurrentResult(): QueryObserverResult[];
```
Defined in: [packages/query-core/src/queriesObserver.ts:210](https://github.com/TanStack/query/blob/main/packages/query-core/src/queriesObserver.ts#L210)
Returns the most recently computed array of `QueryObserverResult`s, one
per observed query, in the same order as the queries passed to the
constructor or `setQueries`.
#### Returns
[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)[]
#### Example
```ts
const results = observer.getCurrentResult()
const data = results.map((result) => result.data)
```
***
### getObservers()
```ts
getObservers(): QueryObserver<unknown, Error, unknown, unknown, readonly unknown[]>[];
```
Defined in: [packages/query-core/src/queriesObserver.ts:227](https://github.com/TanStack/query/blob/main/packages/query-core/src/queriesObserver.ts#L227)
Returns the underlying `QueryObserver` instances this observer manages,
in the same order as the queries passed to the constructor or
`setQueries`.
#### Returns
[`QueryObserver`](QueryObserver.md)\<`unknown`, `Error`, `unknown`, `unknown`, readonly `unknown`[]\>[]
***
### getOptimisticResult()
```ts
getOptimisticResult(queries, combine): [QueryObserverResult[], (r?) => TCombinedResult, () => QueryObserverResult[]];
```
Defined in: [packages/query-core/src/queriesObserver.ts:238](https://github.com/TanStack/query/blob/main/packages/query-core/src/queriesObserver.ts#L238)
The `QueriesObserver` counterpart of [QueryObserver#getOptimisticResult](QueryObserver.md#getoptimisticresult) — computes
the result for the given (already-defaulted) queries right now, synchronously. Called by
framework adapters (e.g. `useQueries`) ahead of subscribing, returning a tuple of the raw
per-query results, a function to compute the combined result from them, and a function to
wrap the results for property-access tracking.
#### Parameters
##### queries
[`QueryObserverOptions`](../interfaces/QueryObserverOptions.md)\<`unknown`, `Error`, `unknown`, `unknown`, readonly `unknown`[], `never`\>[]
##### combine
`CombineFn`\<`TCombinedResult`\> | `undefined`
#### Returns
\[[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)[], (`r?`) => `TCombinedResult`, () => [`QueryObserverResult`](../type-aliases/QueryObserverResult.md)[]\]
***
### getQueries()
```ts
getQueries(): Query<unknown, Error, unknown, readonly unknown[]>[];
```
Defined in: [packages/query-core/src/queriesObserver.ts:218](https://github.com/TanStack/query/blob/main/packages/query-core/src/queriesObserver.ts#L218)
Returns the underlying `Query` instances currently being observed, in
the same order as the queries passed to the constructor or `setQueries`.
#### Returns
[`Query`](Query.md)\<`unknown`, `Error`, `unknown`, readonly `unknown`[]\>[]
***
### hasListeners()
```ts
hasListeners(): boolean;
```
Defined in: [packages/query-core/src/subscribable.ts:19](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L19)
#### Returns
`boolean`
#### Inherited from
```ts
Subscribable.hasListeners
```
***
### onSubscribe()
```ts
protected onSubscribe(): void;
```
Defined in: [packages/query-core/src/queriesObserver.ts:86](https://github.com/TanStack/query/blob/main/packages/query-core/src/queriesObserver.ts#L86)
#### Returns
`void`
#### Overrides
```ts
Subscribable.onSubscribe
```
***
### onUnsubscribe()
```ts
protected onUnsubscribe(): void;
```
Defined in: [packages/query-core/src/queriesObserver.ts:96](https://github.com/TanStack/query/blob/main/packages/query-core/src/queriesObserver.ts#L96)
#### Returns
`void`
#### Overrides
```ts
Subscribable.onUnsubscribe
```
***
### setQueries()
```ts
setQueries(queries, options?): void;
```
Defined in: [packages/query-core/src/queriesObserver.ts:127](https://github.com/TanStack/query/blob/main/packages/query-core/src/queriesObserver.ts#L127)
Replaces the set of queries being observed. Existing `QueryObserver`s
are reused for queries that match an already-observed query hash;
observers for queries that are no longer present are destroyed, and new
observers are created and subscribed to for newly added queries.
#### Parameters
##### queries
[`QueryObserverOptions`](../interfaces/QueryObserverOptions.md)\<`unknown`, `Error`, `unknown`, `unknown`, readonly `unknown`[], `never`\>[]
##### options?
[`QueriesObserverOptions`](../interfaces/QueriesObserverOptions.md)\<`TCombinedResult`\>
#### Returns
`void`
#### Example
```ts
observer.setQueries([
{ queryKey: ['post', 1], queryFn: fetchPost },
{ queryKey: ['post', 3], queryFn: fetchPost },
])
```
***
### subscribe()
```ts
subscribe(listener): () => void;
```
Defined in: [packages/query-core/src/subscribable.ts:8](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L8)
#### Parameters
##### listener
`QueriesObserverListener`
#### Returns
```ts
(): void;
```
##### Returns
`void`
#### Inherited from
```ts
Subscribable.subscribe
```

View File

@@ -0,0 +1,585 @@
---
id: Query
title: Query
---
Defined in: [packages/query-core/src/query.ts:225](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L225)
Represents a single cached query. A `Query` holds the query's key, options,
state (data/error/status), and the observers currently subscribed to it.
Instances are created and managed internally by `QueryCache`; application
code typically interacts with queries indirectly through `QueryClient` or
a framework hook like `useQuery`. Direct access to a `Query` instance is
possible via `queryCache.find()`/`findAll()` for inspecting cache state.
## Example
```ts
const queryCache = queryClient.getQueryCache()
const query = queryCache.find({ queryKey: ['posts'] })
if (query) {
console.log(query.state.dataUpdatedAt)
}
```
## Extends
- `Removable`
## Type Parameters
### TQueryFnData
`TQueryFnData` = `unknown`
### TError
`TError` = [`DefaultError`](../type-aliases/DefaultError.md)
### TData
`TData` = `TQueryFnData`
### TQueryKey
`TQueryKey` *extends* [`QueryKey`](../type-aliases/QueryKey.md) = [`QueryKey`](../type-aliases/QueryKey.md)
## Constructors
### Constructor
```ts
new Query<TQueryFnData, TError, TData, TQueryKey>(config): Query<TQueryFnData, TError, TData, TQueryKey>;
```
Defined in: [packages/query-core/src/query.ts:246](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L246)
#### Parameters
##### config
`QueryConfig`\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
#### Returns
`Query`\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
#### Overrides
```ts
Removable.constructor
```
## Properties
### gcTime
```ts
gcTime: number;
```
Defined in: [packages/query-core/src/removable.ts:7](https://github.com/TanStack/query/blob/main/packages/query-core/src/removable.ts#L7)
#### Inherited from
```ts
Removable.gcTime
```
***
### observers
```ts
observers: QueryObserver<any, any, any, any, any>[];
```
Defined in: [packages/query-core/src/query.ts:242](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L242)
***
### options
```ts
options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>;
```
Defined in: [packages/query-core/src/query.ts:233](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L233)
***
### queryHash
```ts
queryHash: string;
```
Defined in: [packages/query-core/src/query.ts:232](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L232)
***
### queryKey
```ts
queryKey: TQueryKey;
```
Defined in: [packages/query-core/src/query.ts:231](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L231)
***
### state
```ts
state: QueryState<TData, TError>;
```
Defined in: [packages/query-core/src/query.ts:234](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L234)
## Accessors
### meta
#### Get Signature
```ts
get meta(): Record<string, unknown> | undefined;
```
Defined in: [packages/query-core/src/query.ts:264](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L264)
The `meta` object passed in the query's options, if any.
##### Returns
`Record`\<`string`, `unknown`\> \| `undefined`
***
### promise
#### Get Signature
```ts
get promise(): Promise<TData> | undefined;
```
Defined in: [packages/query-core/src/query.ts:277](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L277)
The promise for the currently in-flight fetch, if the query is fetching.
`undefined` when the query is not fetching.
##### Returns
`Promise`\<`TData`\> \| `undefined`
## Methods
### cancel()
```ts
cancel(options?): Promise<void>;
```
Defined in: [packages/query-core/src/query.ts:348](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L348)
Cancels the query's currently in-flight fetch, if any.
- Returns a promise that resolves once the cancellation has settled.
- If no fetch is in progress, resolves immediately.
#### Parameters
##### options?
[`CancelOptions`](../interfaces/CancelOptions.md)
#### Returns
`Promise`\<`void`\>
#### Example
```ts
await query.cancel()
```
***
### clearGcTimeout()
```ts
protected clearGcTimeout(): void;
```
Defined in: [packages/query-core/src/removable.ts:32](https://github.com/TanStack/query/blob/main/packages/query-core/src/removable.ts#L32)
#### Returns
`void`
#### Inherited from
```ts
Removable.clearGcTimeout
```
***
### destroy()
```ts
destroy(): void;
```
Defined in: [packages/query-core/src/query.ts:361](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L361)
Clears the query's garbage collection timeout and silently cancels any
in-flight fetch. Called by `QueryCache` when the query is removed from
the cache.
#### Returns
`void`
#### See
[Query#cancel](#cancel)
#### Overrides
```ts
Removable.destroy
```
***
### fetch()
```ts
fetch(options?, fetchOptions?): Promise<TData>;
```
Defined in: [packages/query-core/src/query.ts:590](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L590)
Fetches the query, i.e. runs its `queryFn` (through any configured
retryer/behavior) and updates the query's state with the result.
- If a fetch is already in flight, returns its promise instead of
starting a new one, unless `fetchOptions.cancelRefetch` is set and the
query already has data, in which case the current fetch is silently
cancelled first.
- If `options` is passed, it replaces the query's current options
before fetching.
#### Parameters
##### options?
[`QueryOptions`](../interfaces/QueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `never`\>
##### fetchOptions?
`FetchOptions`\<`TQueryFnData`\>
#### Returns
`Promise`\<`TData`\>
***
### getObserversCount()
```ts
getObserversCount(): number;
```
Defined in: [packages/query-core/src/query.ts:560](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L560)
Returns the number of observers currently subscribed to this query.
#### Returns
`number`
#### Example
```ts
if (query.getObserversCount() === 0) {
// no component is currently watching this query
}
```
***
### invalidate()
```ts
invalidate(): void;
```
Defined in: [packages/query-core/src/query.ts:574](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L574)
Marks the query as invalidated, unless it is already invalidated. This
updates `state.isInvalidated` and notifies observers, but does not by
itself trigger a refetch.
#### Returns
`void`
#### Example
```ts
query.invalidate()
```
***
### isActive()
```ts
isActive(): boolean;
```
Defined in: [packages/query-core/src/query.ts:386](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L386)
Returns `true` if the query has at least one observer for which `enabled`
does not resolve to `false`.
#### Returns
`boolean`
***
### isDisabled()
```ts
isDisabled(): boolean;
```
Defined in: [packages/query-core/src/query.ts:400](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L400)
Returns `true` if the query is disabled, meaning it will not fetch
automatically.
- If the query has observers, it is disabled when none of them are active
(see `isActive`).
- If the query has no observers, it is disabled when its `queryFn` is
`skipToken` or it has never been fetched.
#### Returns
`boolean`
***
### isFetched()
```ts
isFetched(): boolean;
```
Defined in: [packages/query-core/src/query.ts:412](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L412)
Returns `true` if the query has been fetched, i.e. it has resolved with
either data or an error at least once.
#### Returns
`boolean`
***
### isStale()
```ts
isStale(): boolean;
```
Defined in: [packages/query-core/src/query.ts:447](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L447)
Returns `true` if the query is stale.
- If the query has observers, defers to whether any observer's current
result reports `isStale` (which accounts for each observer's own
`staleTime` and `enabled` state).
- If the query has no observers, it is considered stale when it has no
data or has been invalidated.
#### Returns
`boolean`
#### See
[Query#isStaleByTime](#isstalebytime)
#### Example
```ts
if (query.isStale()) {
// refetch or otherwise treat the cached data as outdated
}
```
***
### isStaleByTime()
```ts
isStaleByTime(staleTime): boolean;
```
Defined in: [packages/query-core/src/query.ts:473](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L473)
Returns `true` if the query's data is stale relative to the given
`staleTime` (defaults to `0`).
- A query with no data is always stale.
- `staleTime: 'static'` is never stale.
- An invalidated query is always stale.
- Otherwise, staleness is based on elapsed time since `dataUpdatedAt`.
#### Parameters
##### staleTime
[`StaleTime`](../type-aliases/StaleTime.md) = `0`
#### Returns
`boolean`
#### See
[Query#isStale](#isstale)
#### Example
```ts
const isStale = query.isStaleByTime(1000 * 60)
```
***
### isStatic()
```ts
isStatic(): boolean;
```
Defined in: [packages/query-core/src/query.ts:420](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L420)
Returns `true` if the query has at least one observer configured with
`staleTime: 'static'`, meaning it is treated as never stale.
#### Returns
`boolean`
***
### optionalRemove()
```ts
protected optionalRemove(): void;
```
Defined in: [packages/query-core/src/query.ts:305](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L305)
#### Returns
`void`
#### Overrides
```ts
Removable.optionalRemove
```
***
### reset()
```ts
reset(): void;
```
Defined in: [packages/query-core/src/query.ts:377](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L377)
Resets the query back to its initial state (the state it had when it was
first created, e.g. any `initialData`), destroying it first to cancel any
in-flight fetch.
#### Returns
`void`
***
### scheduleGc()
```ts
protected scheduleGc(): void;
```
Defined in: [packages/query-core/src/removable.ts:14](https://github.com/TanStack/query/blob/main/packages/query-core/src/removable.ts#L14)
#### Returns
`void`
#### Inherited from
```ts
Removable.scheduleGc
```
***
### setState()
```ts
setState(state): void;
```
Defined in: [packages/query-core/src/query.ts:334](https://github.com/TanStack/query/blob/main/packages/query-core/src/query.ts#L334)
Merges the given partial state directly into this query's state, notifying observers. Used
by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a
user manually trigger a loading/error state or edit the cached data.
#### Parameters
##### state
`Partial`\<[`QueryState`](../interfaces/QueryState.md)\<`TData`, `TError`\>\>
#### Returns
`void`
***
### updateGcTime()
```ts
protected updateGcTime(newGcTime): void;
```
Defined in: [packages/query-core/src/removable.ts:24](https://github.com/TanStack/query/blob/main/packages/query-core/src/removable.ts#L24)
#### Parameters
##### newGcTime
`number` | `undefined`
#### Returns
`void`
#### Inherited from
```ts
Removable.updateGcTime
```

View File

@@ -0,0 +1,471 @@
---
id: QueryCache
title: QueryCache
---
Defined in: [packages/query-core/src/queryCache.ts:123](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryCache.ts#L123)
The `QueryCache` is the storage mechanism for TanStack Query. It stores all the data, meta
information, and state of the queries it contains.
Normally, you will not interact with the `QueryCache` directly and instead use a `QueryClient`
for a specific cache. You can subscribe to it (inherited from `Subscribable`) to be informed of
safe/known updates to the cache, such as queries being added, removed, or updated — updates made
outside of the cache's own tracked mechanisms (e.g. mutating a query's state object directly) do
not notify subscribers.
## Example
```ts
const unsubscribe = queryCache.subscribe((event) => {
console.log(event.type, event.query)
})
```
## Extends
- `Subscribable`\<`QueryCacheListener`\>
## Constructors
### Constructor
```ts
new QueryCache(config): QueryCache;
```
Defined in: [packages/query-core/src/queryCache.ts:126](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryCache.ts#L126)
#### Parameters
##### config
[`QueryCacheConfig`](../interfaces/QueryCacheConfig.md) = `{}`
#### Returns
`QueryCache`
#### Overrides
```ts
Subscribable<QueryCacheListener>.constructor
```
## Properties
### config
```ts
config: QueryCacheConfig = {};
```
Defined in: [packages/query-core/src/queryCache.ts:126](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryCache.ts#L126)
***
### listeners
```ts
protected listeners: Set<QueryCacheListener>;
```
Defined in: [packages/query-core/src/subscribable.ts:2](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L2)
#### Inherited from
```ts
Subscribable.listeners
```
## Methods
### build()
```ts
build<TQueryFnData, TError, TData, TQueryKey>(
client,
options,
state?): Query<TQueryFnData, TError, TData, TQueryKey>;
```
Defined in: [packages/query-core/src/queryCache.ts:147](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryCache.ts#L147)
Returns the existing `Query` instance for the given options' `queryKey`/`queryHash`, or
builds and adds a new one to the cache if none exists yet. Used by framework adapters and
plugins (e.g. broadcast/persistence) that need to get-or-create a `Query` directly, bypassing
the reactive `QueryObserver` machinery.
#### Type Parameters
##### TQueryFnData
`TQueryFnData` = `unknown`
##### TError
`TError` = `Error`
##### TData
`TData` = `TQueryFnData`
##### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
#### Parameters
##### client
[`QueryClient`](QueryClient.md)
##### options
[`WithRequired`](../type-aliases/WithRequired.md)\<[`QueryOptions`](../interfaces/QueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `never`\>, `"queryKey"`\>
##### state?
[`QueryState`](../interfaces/QueryState.md)\<`TData`, `TError`\>
#### Returns
[`Query`](Query.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
#### Example
```ts
const queryCache = queryClient.getQueryCache()
const query = queryCache.build(queryClient, {
queryKey: ['posts'],
queryFn: fetchPosts,
})
```
***
### clear()
```ts
clear(): void;
```
Defined in: [packages/query-core/src/queryCache.ts:232](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryCache.ts#L232)
Removes all queries from the cache.
#### Returns
`void`
#### Example
```ts
const queryCache = queryClient.getQueryCache()
queryCache.clear()
```
***
### find()
```ts
find<TQueryFnData, TError, TData>(filters):
| Query<TQueryFnData, TError, TData, readonly unknown[]>
| undefined;
```
Defined in: [packages/query-core/src/queryCache.ts:299](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryCache.ts#L299)
A slightly more advanced method that can be used to get an existing query instance from the
cache. This instance not only contains all the state for the query, but all of the instances,
and underlying guts of the query as well. If the query does not exist, `undefined` is
returned.
This is not typically needed for most applications, but can come in handy when needing more
information about a query in rare scenarios (e.g. looking at `query.state.dataUpdatedAt` to
decide whether a query is fresh enough to be used as an initial value).
#### Type Parameters
##### TQueryFnData
`TQueryFnData` = `unknown`
##### TError
`TError` = `Error`
##### TData
`TData` = `TQueryFnData`
#### Parameters
##### filters
[`WithRequired`](../type-aliases/WithRequired.md)\<[`QueryFilters`](../interfaces/QueryFilters.md)\<readonly `unknown`[]\>, `"queryKey"`\>
#### Returns
\| [`Query`](Query.md)\<`TQueryFnData`, `TError`, `TData`, readonly `unknown`[]\>
\| `undefined`
#### See
[QueryCache#findAll](#findall)
#### Example
```ts
const queryCache = queryClient.getQueryCache()
const query = queryCache.find({ queryKey: ['posts'] })
```
***
### findAll()
```ts
findAll(filters): Query<unknown, Error, unknown, readonly unknown[]>[];
```
Defined in: [packages/query-core/src/queryCache.ts:324](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryCache.ts#L324)
An even more advanced method that can be used to get existing query instances from the cache
that partially match a query key. If no queries match, an empty array is returned.
This is not typically needed for most applications, but can come in handy when needing more
information about queries in rare scenarios.
#### Parameters
##### filters
[`QueryFilters`](../interfaces/QueryFilters.md)\<`any`\> = `{}`
#### Returns
[`Query`](Query.md)\<`unknown`, `Error`, `unknown`, readonly `unknown`[]\>[]
#### See
[QueryCache#find](#find)
#### Example
```ts
const queryCache = queryClient.getQueryCache()
const queries = queryCache.findAll({ queryKey: ['posts'] })
```
***
### get()
```ts
get<TQueryFnData, TError, TData, TQueryKey>(queryHash):
| Query<TQueryFnData, TError, TData, TQueryKey>
| undefined;
```
Defined in: [packages/query-core/src/queryCache.ts:254](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryCache.ts#L254)
Returns the `Query` instance stored under the given `queryHash`, or `undefined` if none
exists. Unlike [QueryCache#find](#find), this looks up by the already-computed hash rather
than by `QueryFilters`. Used by plugins (e.g. broadcast/hydration) that already have a hash
to look up directly.
#### Type Parameters
##### TQueryFnData
`TQueryFnData` = `unknown`
##### TError
`TError` = `Error`
##### TData
`TData` = `TQueryFnData`
##### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
#### Parameters
##### queryHash
`string`
#### Returns
\| [`Query`](Query.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
\| `undefined`
#### Example
```ts
const queryCache = queryClient.getQueryCache()
const queryHash = hashKey(['posts'])
const query = queryCache.get(queryHash)
```
***
### getAll()
```ts
getAll(): Query<unknown, Error, unknown, readonly unknown[]>[];
```
Defined in: [packages/query-core/src/queryCache.ts:277](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryCache.ts#L277)
Returns all queries within the cache.
#### Returns
[`Query`](Query.md)\<`unknown`, `Error`, `unknown`, readonly `unknown`[]\>[]
#### Example
```ts
const queryCache = queryClient.getQueryCache()
const queries = queryCache.getAll()
```
***
### hasListeners()
```ts
hasListeners(): boolean;
```
Defined in: [packages/query-core/src/subscribable.ts:19](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L19)
#### Returns
`boolean`
#### Inherited from
```ts
Subscribable.hasListeners
```
***
### onSubscribe()
```ts
protected onSubscribe(): void;
```
Defined in: [packages/query-core/src/subscribable.ts:23](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L23)
#### Returns
`void`
#### Inherited from
```ts
Subscribable.onSubscribe
```
***
### onUnsubscribe()
```ts
protected onUnsubscribe(): void;
```
Defined in: [packages/query-core/src/subscribable.ts:27](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L27)
#### Returns
`void`
#### Inherited from
```ts
Subscribable.onUnsubscribe
```
***
### remove()
```ts
remove(query): void;
```
Defined in: [packages/query-core/src/queryCache.ts:208](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryCache.ts#L208)
Destroys the given `Query` and removes it from the cache, notifying subscribers with a
`'removed'` event. A no-op if the query is no longer the one currently stored under its hash
(e.g. it was already replaced). Used by plugins (e.g. the broadcast client) that mirror
removals across `QueryCache` instances.
#### Parameters
##### query
[`Query`](Query.md)\<`any`, `any`, `any`, `any`\>
#### Returns
`void`
#### Example
```ts
const queryCache = queryClient.getQueryCache()
const query = queryCache.find({ queryKey: ['posts'] })
if (query) {
queryCache.remove(query)
}
```
***
### subscribe()
```ts
subscribe(listener): () => void;
```
Defined in: [packages/query-core/src/subscribable.ts:8](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L8)
#### Parameters
##### listener
`QueryCacheListener`
#### Returns
```ts
(): void;
```
##### Returns
`void`
#### Inherited from
```ts
Subscribable.subscribe
```

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,555 @@
---
id: QueryObserver
title: QueryObserver
---
Defined in: [packages/query-core/src/queryObserver.ts:57](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L57)
A `QueryObserver` watches a single query in the `QueryCache` and computes a
`QueryObserverResult` from its state, recomputing and notifying subscribers
whenever the underlying query (or the observer's options) changes. It is
the primitive that framework adapters (e.g. `useQuery`) build their hooks
on top of, but it can also be used directly to observe and switch between
queries outside of any framework.
## Example
```ts
const observer = new QueryObserver(queryClient, {
queryKey: ['posts'],
queryFn: fetchPosts,
})
const unsubscribe = observer.subscribe((result) => {
console.log(result.data)
})
```
## Extends
- `Subscribable`\<`QueryObserverListener`\<`TData`, `TError`\>\>
## Extended by
- [`InfiniteQueryObserver`](InfiniteQueryObserver.md)
## Type Parameters
### TQueryFnData
`TQueryFnData` = `unknown`
### TError
`TError` = [`DefaultError`](../type-aliases/DefaultError.md)
### TData
`TData` = `TQueryFnData`
### TQueryData
`TQueryData` = `TQueryFnData`
### TQueryKey
`TQueryKey` *extends* [`QueryKey`](../type-aliases/QueryKey.md) = [`QueryKey`](../type-aliases/QueryKey.md)
## Constructors
### Constructor
```ts
new QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>(client, options): QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>;
```
Defined in: [packages/query-core/src/queryObserver.ts:87](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L87)
#### Parameters
##### client
[`QueryClient`](QueryClient.md)
##### options
[`QueryObserverOptions`](../interfaces/QueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>
#### Returns
`QueryObserver`\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>
#### Overrides
```ts
Subscribable<QueryObserverListener<TData, TError>>.constructor
```
## Properties
### listeners
```ts
protected listeners: Set<QueryObserverListener<TData, TError>>;
```
Defined in: [packages/query-core/src/subscribable.ts:2](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L2)
#### Inherited from
```ts
Subscribable.listeners
```
***
### options
```ts
options: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>;
```
Defined in: [packages/query-core/src/queryObserver.ts:89](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L89)
## Methods
### bindMethods()
```ts
protected bindMethods(): void;
```
Defined in: [packages/query-core/src/queryObserver.ts:106](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L106)
#### Returns
`void`
***
### createResult()
```ts
protected createResult(query, options): QueryObserverResult<TData, TError>;
```
Defined in: [packages/query-core/src/queryObserver.ts:559](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L559)
#### Parameters
##### query
[`Query`](Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>
##### options
[`QueryObserverOptions`](../interfaces/QueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>
#### Returns
[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
***
### destroy()
```ts
destroy(): void;
```
Defined in: [packages/query-core/src/queryObserver.ts:161](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L161)
Stops observing the current query: clears all listeners, cancels the
stale and refetch-interval timers, and removes this observer from the
query it was observing.
#### Returns
`void`
***
### fetch()
```ts
protected fetch(fetchOptions): Promise<QueryObserverResult<TData, TError>>;
```
Defined in: [packages/query-core/src/queryObserver.ts:448](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L448)
#### Parameters
##### fetchOptions
`ObserverFetchOptions`
#### Returns
`Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\>
***
### fetchOptimistic()
```ts
fetchOptimistic(options): Promise<QueryObserverResult<TData, TError>>;
```
Defined in: [packages/query-core/src/queryObserver.ts:395](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L395)
Fetches a query defined by the given options without affecting this
observer's own tracked query or result, and returns a promise that
resolves with the `QueryObserverResult` for that fetch. This is useful
for prefetching data that another observer (e.g. a query about to be
navigated to) will need, ahead of time.
#### Parameters
##### options
[`QueryObserverOptions`](../interfaces/QueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>
#### Returns
`Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\>
#### Example
```ts
const result = await observer.fetchOptimistic({
queryKey: ['posts', 2],
queryFn: () => fetchPost(2),
})
console.log(result.data)
```
***
### getCurrentQuery()
```ts
getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey>;
```
Defined in: [packages/query-core/src/queryObserver.ts:357](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L357)
Returns the `Query` instance this observer is currently observing.
#### Returns
[`Query`](Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>
***
### getCurrentResult()
```ts
getCurrentResult(): QueryObserverResult<TData, TError>;
```
Defined in: [packages/query-core/src/queryObserver.ts:321](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L321)
Returns the most recently computed `QueryObserverResult` for the
observed query. This is a point-in-time read; to be notified of updates
as they happen, subscribe to the observer instead (its inherited
`subscribe` method).
#### Returns
[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
#### Example
```ts
const result = observer.getCurrentResult()
console.log(result.status, result.data)
```
***
### getOptimisticResult()
```ts
getOptimisticResult(options): QueryObserverResult<TData, TError>;
```
Defined in: [packages/query-core/src/queryObserver.ts:272](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L272)
Computes the result the observer would produce for the given (already-defaulted) options
right now, building the underlying `Query` if it doesn't exist yet, without waiting for a
subscription callback. Called by framework adapters on every render (e.g. `useQuery`) so the
returned value is available synchronously, ahead of `setOptions` triggering an actual fetch.
#### Parameters
##### options
[`DefaultedQueryObserverOptions`](../type-aliases/DefaultedQueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>
#### Returns
[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
***
### hasListeners()
```ts
hasListeners(): boolean;
```
Defined in: [packages/query-core/src/subscribable.ts:19](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L19)
#### Returns
`boolean`
#### Inherited from
```ts
Subscribable.hasListeners
```
***
### onSubscribe()
```ts
protected onSubscribe(): void;
```
Defined in: [packages/query-core/src/queryObserver.ts:110](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L110)
#### Returns
`void`
#### Overrides
```ts
Subscribable.onSubscribe
```
***
### onUnsubscribe()
```ts
protected onUnsubscribe(): void;
```
Defined in: [packages/query-core/src/queryObserver.ts:124](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L124)
#### Returns
`void`
#### Overrides
```ts
Subscribable.onUnsubscribe
```
***
### refetch()
```ts
refetch(__namedParameters): Promise<QueryObserverResult<TData, TError>>;
```
Defined in: [packages/query-core/src/queryObserver.ts:371](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L371)
Refetches the observed query and returns a promise that resolves with
the resulting `QueryObserverResult`.
#### Parameters
##### \_\_namedParameters
[`RefetchOptions`](../interfaces/RefetchOptions.md) = `{}`
#### Returns
`Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\>
#### Example
```ts
const result = await observer.refetch({ cancelRefetch: false })
console.log(result.data)
```
***
### setOptions()
```ts
setOptions(options): void;
```
Defined in: [packages/query-core/src/queryObserver.ts:182](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L182)
Updates the observer's options. This will re-resolve the query being
observed (switching to a different query if the `queryKey` changed),
trigger a fetch if the new options require one and the observer has
subscribers, recompute the current result, and reschedule the stale and
refetch-interval timers as needed.
#### Parameters
##### options
[`QueryObserverOptions`](../interfaces/QueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>
#### Returns
`void`
#### Example
```ts
observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) })
// later: switch to a different query, reusing the same observer
observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) })
```
***
### shouldFetchOnReconnect()
```ts
shouldFetchOnReconnect(): boolean;
```
Defined in: [packages/query-core/src/queryObserver.ts:135](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L135)
Returns whether the observed query is currently stale and configured
(via the `refetchOnReconnect` option) to refetch when the network
reconnects.
#### Returns
`boolean`
***
### shouldFetchOnWindowFocus()
```ts
shouldFetchOnWindowFocus(): boolean;
```
Defined in: [packages/query-core/src/queryObserver.ts:148](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L148)
Returns whether the observed query is currently stale and configured
(via the `refetchOnWindowFocus` option) to refetch when the window
regains focus.
#### Returns
`boolean`
***
### subscribe()
```ts
subscribe(listener): () => void;
```
Defined in: [packages/query-core/src/subscribable.ts:8](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L8)
#### Parameters
##### listener
`QueryObserverListener`
#### Returns
```ts
(): void;
```
##### Returns
`void`
#### Inherited from
```ts
Subscribable.subscribe
```
***
### trackProp()
```ts
trackProp(key): void;
```
Defined in: [packages/query-core/src/queryObserver.ts:350](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L350)
Records that the given `QueryObserverResult` property was read, so a subsequent update only
notifies this observer if a tracked property actually changed. Normally called indirectly via
[QueryObserver#trackResult](#trackresult)'s proxy; exposed directly for adapters that track property
access themselves (e.g. through their own reactivity system) instead of via the proxy.
#### Parameters
##### key
`"error"` | `"data"` | `"isError"` | `"isPending"` | `"isLoading"` | `"isLoadingError"` | `"isRefetchError"` | `"isSuccess"` | `"isPlaceholderData"` | `"status"` | `"dataUpdatedAt"` | `"errorUpdatedAt"` | `"failureCount"` | `"failureReason"` | `"errorUpdateCount"` | `"isFetched"` | `"isFetchedAfterMount"` | `"isFetching"` | `"isInitialLoading"` | `"isPaused"` | `"isRefetching"` | `"isStale"` | `"isEnabled"` | `"refetch"` | `"fetchStatus"`
#### Returns
`void`
***
### trackResult()
```ts
trackResult(result, onPropTracked?): QueryObserverResult<TData, TError>;
```
Defined in: [packages/query-core/src/queryObserver.ts:331](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L331)
Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via
[QueryObserver#trackProp](#trackprop) (and an optional `onPropTracked` callback). Used by framework
adapters when `notifyOnChangeProps` is not set, to implement its default "only re-render on
properties you actually read" behavior.
#### Parameters
##### result
[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
##### onPropTracked?
(`key`) => `void`
#### Returns
[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
***
### updateResult()
```ts
updateResult(): void;
```
Defined in: [packages/query-core/src/queryObserver.ts:735](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L735)
Recomputes and stores the current result from the current query/options, notifying listeners
if it changed. Framework adapters call this right after subscribing to make sure no query
update was missed in the gap between creating the observer and subscribing to it.
#### Returns
`void`

View File

@@ -0,0 +1,62 @@
---
id: HydrationBoundary
title: HydrationBoundary
---
```ts
function HydrationBoundary(__namedParameters): Element;
```
Defined in: [packages/preact-query/src/HydrationBoundary.tsx:87](https://github.com/TanStack/query/blob/main/packages/preact-query/src/HydrationBoundary.tsx#L87)
`HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by
`useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on
update timestamp.
Note: Only `queries` can be dehydrated with an `HydrationBoundary`.
## Parameters
### \_\_namedParameters
[`HydrationBoundaryProps`](../interfaces/HydrationBoundaryProps.md)
## Returns
`Element`
The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the
cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect
after commit.
## Examples
```tsx
import { HydrationBoundary } from '@tanstack/preact-query'
function App() {
return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>
}
```
Server-side prefetch handed off to the client via `dehydrate`:
```tsx
import { HydrationBoundary, dehydrate, noop } from '@tanstack/preact-query'
async function ServerComponent() {
const queryClient = getQueryClient()
await queryClient
.query({
queryKey: ['posts'],
queryFn: fetchPosts,
})
.catch(noop)
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<Posts />
</HydrationBoundary>
)
}
```

View File

@@ -0,0 +1,39 @@
---
id: QueryClientProvider
title: QueryClientProvider
---
```ts
function QueryClientProvider(__namedParameters): VNode;
```
Defined in: [packages/preact-query/src/QueryClientProvider.tsx:70](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryClientProvider.tsx#L70)
Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also
calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to
focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or
comes back online).
## Parameters
### \_\_namedParameters
[`QueryClientProviderProps`](../type-aliases/QueryClientProviderProps.md)
## Returns
`VNode`
The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.
## Example
```tsx
import { QueryClient, QueryClientProvider } from '@tanstack/preact-query'
const queryClient = new QueryClient()
function App() {
return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
}
```

View File

@@ -0,0 +1,68 @@
---
id: QueryErrorResetBoundary
title: QueryErrorResetBoundary
---
```ts
function QueryErrorResetBoundary(__namedParameters): Element;
```
Defined in: [packages/preact-query/src/QueryErrorResetBoundary.tsx:159](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L159)
When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to
try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can
reset any query errors within the boundaries of the component.
## Parameters
### \_\_namedParameters
[`QueryErrorResetBoundaryProps`](../interfaces/QueryErrorResetBoundaryProps.md)
## Returns
`Element`
The `children`, rendered as-is, or called with the boundary's QueryErrorResetBoundaryValue
if `children` is a function.
## Example
```tsx
import { useErrorBoundary } from 'preact/hooks'
import type { ComponentChildren } from 'preact'
import { QueryErrorResetBoundary } from '@tanstack/preact-query'
function App() {
return (
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary reset={reset}>
<Page />
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
)
}
function ErrorBoundary({
children,
reset,
}: {
children: ComponentChildren
reset: () => void
}) {
const [error, resetError] = useErrorBoundary(() => reset())
if (error) {
return (
<div>
There was an error!
<button onClick={() => resetError()}>Try again</button>
</div>
)
}
return children
}
```

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,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,256 @@
---
id: infiniteQueryOptions
title: infiniteQueryOptions
---
## Call Signature
```ts
function infiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options): UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & object & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData, unknown>, TError>;
```
Defined in: [packages/preact-query/src/infiniteQueryOptions.ts:171](https://github.com/TanStack/query/blob/main/packages/preact-query/src/infiniteQueryOptions.ts#L171)
You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
These options can be shared across hooks 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 `useInfiniteQuery`, with `initialData` set.
### Returns
The same options object, typed so that `queryKey` carries the inferred data type.
### See
[useInfiniteQuery](useInfiniteQuery.md) to run an infinite query with these options.
### Remarks
See [useInfiniteQuery](useInfiniteQuery.md) for examples that fetch further pages, from a button click or
automatically as the user scrolls.
### Example
```tsx
import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/preact-query'
export const projectsOptions = infiniteQueryOptions({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
initialData: { pages: [], pageParams: [] },
})
function Projects() {
// `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
// list stays visible alongside the error.
const { data, isError, error } = useInfiniteQuery(projectsOptions)
return (
<div>
{isError ? <span>Error: {error.message}</span> : null}
<ul>
{data.pages.map((page) => page.projects.map((p) => <li key={p.id}>{p.name}</li>))}
</ul>
</div>
)
}
```
## Call Signature
```ts
function infiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options): OmitKeyof<UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, "queryFn"> & object & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData, unknown>, TError>;
```
Defined in: [packages/preact-query/src/infiniteQueryOptions.ts:233](https://github.com/TanStack/query/blob/main/packages/preact-query/src/infiniteQueryOptions.ts#L233)
You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
These options can be shared across hooks 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
[`UnusedSkipTokenInfiniteOptions`](../type-aliases/UnusedSkipTokenInfiniteOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
The [UnusedSkipTokenInfiniteOptions](../type-aliases/UnusedSkipTokenInfiniteOptions.md) to use — everything you can pass to `useInfiniteQuery`.
### Returns
The same options object, typed so that `queryKey` carries the inferred data type.
### Remarks
See [useInfiniteQuery](useInfiniteQuery.md) for examples that fetch further pages, from a button click or
automatically as the user scrolls.
### Example
A parameterized factory, so the same options object can be reused per `postId`:
```tsx
import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/preact-query'
export const commentsOptions = (postId: string) =>
infiniteQueryOptions({
queryKey: ['post', postId, 'comments'],
queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
})
function Comments({ postId }: { postId: string }) {
const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId))
if (isPending) return 'Loading...'
if (isError) return <span>Error: {error.message}</span>
return (
<ul>
{data.pages.map((page) => page.comments.map((c) => <li key={c.id}>{c.text}</li>))}
</ul>
)
}
```
### See
[useInfiniteQuery](useInfiniteQuery.md) to run an infinite query with these options.
## Call Signature
```ts
function infiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options): UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & object & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData, unknown>, TError>;
```
Defined in: [packages/preact-query/src/infiniteQueryOptions.ts:295](https://github.com/TanStack/query/blob/main/packages/preact-query/src/infiniteQueryOptions.ts#L295)
You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`.
These options can be shared across hooks 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 `useInfiniteQuery`.
### Returns
The same options object, typed so that `queryKey` carries the inferred data type.
### Remarks
See [useInfiniteQuery](useInfiniteQuery.md) for examples that fetch further pages (from a button click or
automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set.
### Example
A parameterized factory, so the same options object can be reused per `postId`:
```tsx
import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/preact-query'
export const commentsOptions = (postId: string) =>
infiniteQueryOptions({
queryKey: ['post', postId, 'comments'],
queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
})
function Comments({ postId }: { postId: string }) {
const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId))
if (isPending) return 'Loading...'
if (isError) return <span>Error: {error.message}</span>
return (
<ul>
{data.pages.map((page) => page.comments.map((c) => <li key={c.id}>{c.text}</li>))}
</ul>
)
}
```
### See
[useInfiniteQuery](useInfiniteQuery.md) to run an infinite query with these options.

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,142 @@
---
id: mutationOptions
title: mutationOptions
---
## Call Signature
```ts
function mutationOptions<TData, TError, TVariables, TOnMutateResult>(options): WithRequired<UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, "mutationKey">;
```
Defined in: [packages/preact-query/src/mutationOptions.ts:34](https://github.com/TanStack/query/blob/main/packages/preact-query/src/mutationOptions.ts#L34)
You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A
`mutationKey` is required on this overload so the mutation can be looked up later, 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)\<[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
The mutation options to use, identical to what you'd pass to `useMutation`, with a
required `mutationKey`.
### Returns
[`WithRequired`](../type-aliases/WithRequired.md)\<[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
The same options object, unchanged.
### See
[useMutation](useMutation.md) to run the mutation these options describe.
### Example
Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator:
```tsx
import { mutationOptions, useMutationState } from '@tanstack/preact-query'
const createPostOptions = mutationOptions({
mutationKey: ['posts', 'create'],
mutationFn: createPost,
})
function SavingIndicator() {
const isCreatingPost = useMutationState({
filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' },
}).length > 0
return isCreatingPost ? <span>Saving…</span> : null
}
```
## Call Signature
```ts
function mutationOptions<TData, TError, TVariables, TOnMutateResult>(options): Omit<UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, "mutationKey">;
```
Defined in: [packages/preact-query/src/mutationOptions.ts:74](https://github.com/TanStack/query/blob/main/packages/preact-query/src/mutationOptions.ts#L74)
You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No
`mutationKey` is required on this overload — use this when you don't need to target the mutation via a
`mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters,
such as `status`.
### Type Parameters
#### TData
`TData` = `unknown`
#### TError
`TError` = `Error`
#### TVariables
`TVariables` = `void`
#### TOnMutateResult
`TOnMutateResult` = `unknown`
### Parameters
#### options
`Omit`\<[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
The mutation options to use, identical to what you'd pass to `useMutation`, without a
`mutationKey`.
### Returns
`Omit`\<[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>, `"mutationKey"`\>
The same options object, unchanged.
### See
[useMutation](useMutation.md) to run the mutation these options describe.
### Remarks
See the other overload's example for looking a mutation up via `useMutationState`.
### Example
```tsx
import { mutationOptions, useMutation } from '@tanstack/preact-query'
export const createPostOptions = mutationOptions({
mutationFn: createPost,
})
function CreatePost() {
const mutation = useMutation(createPostOptions)
return <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,243 @@
---
id: queryOptions
title: queryOptions
---
## Call Signature
```ts
function queryOptions<TQueryFnData, TError, TData, TQueryKey>(options): Omit<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, "queryFn"> & object & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
```
Defined in: [packages/preact-query/src/queryOptions.ts:143](https://github.com/TanStack/query/blob/main/packages/preact-query/src/queryOptions.ts#L143)
You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
be shared across hooks 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 `useQuery`, with `initialData` set.
### Returns
The same options object, typed so that `queryKey` carries the inferred data type.
### See
- [useQuery](useQuery.md) to run a query with these options.
- [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
### Example
```tsx
import { queryOptions, useQuery } from '@tanstack/preact-query'
export const postsOptions = queryOptions({
queryKey: ['posts'],
queryFn: fetchPosts,
initialData: [],
})
function Posts() {
// `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails,
// so the list stays visible alongside the error.
const { data, isError, error } = useQuery(postsOptions)
return (
<div>
{isError ? <span>Error: {error.message}</span> : null}
<ul>
{data.map((post) => <li key={post.id}>{post.title}</li>)}
</ul>
</div>
)
}
```
## Call Signature
```ts
function queryOptions<TQueryFnData, TError, TData, TQueryKey>(options): OmitKeyof<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, "queryFn"> & object & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
```
Defined in: [packages/preact-query/src/queryOptions.ts:184](https://github.com/TanStack/query/blob/main/packages/preact-query/src/queryOptions.ts#L184)
You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
be shared across hooks 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
[`UnusedSkipTokenOptions`](../type-aliases/UnusedSkipTokenOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
The [UnusedSkipTokenOptions](../type-aliases/UnusedSkipTokenOptions.md) to use — everything you can pass to `useQuery`.
### Returns
The same options object, typed so that `queryKey` carries the inferred data type.
### See
- [useQuery](useQuery.md) to run a query with these options.
- [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
### Example
A parameterized factory, so the same options object can be reused per `id`:
```tsx
import { queryOptions, useQuery } from '@tanstack/preact-query'
export const postOptions = (id: string) =>
queryOptions({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
})
function Post({ id }: { id: string }) {
const { data, isPending, isError, error } = useQuery(postOptions(id))
if (isPending) return 'Loading...'
if (isError) return <span>Error: {error.message}</span>
return <h1>{data.title}</h1>
}
```
## Call Signature
```ts
function queryOptions<TQueryFnData, TError, TData, TQueryKey>(options): UseQueryOptions<TQueryFnData, TError, TData, TQueryKey> & object & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
```
Defined in: [packages/preact-query/src/queryOptions.ts:248](https://github.com/TanStack/query/blob/main/packages/preact-query/src/queryOptions.ts#L248)
You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
be shared across hooks 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 `useQuery`.
### Returns
The same options object, typed so that `queryKey` carries the inferred data type.
### See
- [useQuery](useQuery.md) to run a query with these options.
- [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
### Remarks
This is the only overload that accepts `queryFn: skipToken`, shown below.
### Examples
A parameterized factory, so the same options object can be reused per `id`:
```tsx
import { queryOptions, useQuery } from '@tanstack/preact-query'
export const postOptions = (id: string) =>
queryOptions({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
})
function Post({ id }: { id: string }) {
const { data, isPending, isError, error } = useQuery(postOptions(id))
if (isPending) return 'Loading...'
if (isError) return <span>Error: {error.message}</span>
return <h1>{data.title}</h1>
}
```
A factory that disables the query, type safe, until `postId` is set:
```tsx
import { queryOptions, skipToken, useQuery } from '@tanstack/preact-query'
export const postOptions = (postId: number | undefined) =>
queryOptions({
queryKey: ['post', postId],
queryFn: postId != null ? () => fetchPost(postId) : skipToken,
})
function Post({ postId }: { postId: number | undefined }) {
const { data, isLoading, isError, error } = useQuery(postOptions(postId))
if (postId == null) return 'Select a post'
if (isLoading) return 'Loading...'
if (isError) return <span>Error: {error.message}</span>
return <h1>{data?.title}</h1>
}
```

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,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,449 @@
---
id: useInfiniteQuery
title: useInfiniteQuery
---
## Call Signature
```ts
function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options, queryClient?): DefinedUseInfiniteQueryResult<TData, TError>;
```
Defined in: [packages/preact-query/src/useInfiniteQuery.ts:65](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useInfiniteQuery.ts#L65)
The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
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 `useInfiniteQuery`, with `initialData` set.
#### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
### Returns
[`DefinedUseInfiniteQueryResult`](../type-aliases/DefinedUseInfiniteQueryResult.md)\<`TData`, `TError`\>
The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
`InfiniteData<TQueryFnData>` shape.
### Remarks
Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
actions, or add conditions like `hasNextPage && !isFetching`.
### See
[infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
### Example
```tsx
import { useInfiniteQuery } from '@tanstack/preact-query'
function Projects() {
// `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
// list stays visible alongside the error.
const { data, isError, error } = useInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
initialData: { pages: [], pageParams: [] },
})
return (
<div>
{isError ? <span>Error: {error.message}</span> : null}
<ul>
{data.pages.map((page) => page.projects.map((p) => <li key={p.id}>{p.name}</li>))}
</ul>
</div>
)
}
```
## Call Signature
```ts
function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options, queryClient?): UseInfiniteQueryResult<TData, TError>;
```
Defined in: [packages/preact-query/src/useInfiniteQuery.ts:191](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useInfiniteQuery.ts#L191)
The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
### 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 `useInfiniteQuery`.
#### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
### Returns
[`UseInfiniteQueryResult`](../type-aliases/UseInfiniteQueryResult.md)\<`TData`, `TError`\>
The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
`InfiniteData<TQueryFnData>` shape.
### Remarks
Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
actions, or add conditions like `hasNextPage && !isFetching`.
### See
[infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
### Examples
Fetching the next page from a "Load More" button click:
```tsx
import { useInfiniteQuery } from '@tanstack/preact-query'
function Projects() {
const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
useInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
})
if (isPending) return 'Loading...'
if (isError) return <span>Error: {error.message}</span>
return (
<>
<ul>
{data.pages.map((page) =>
page.projects.map((project) => <li key={project.id}>{project.name}</li>),
)}
</ul>
<button
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetching}
>
{isFetchingNextPage
? 'Loading more...'
: hasNextPage
? 'Load More'
: 'Nothing more to load'}
</button>
</>
)
}
```
Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
sentinel element after the list:
```tsx
import { useInfiniteQuery } from '@tanstack/preact-query'
import { useEffect, useRef } from 'preact/hooks'
function Projects() {
const {
data,
isPending,
isError,
error,
fetchNextPage,
hasNextPage,
isFetching,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
})
const sentinelRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const sentinel = sentinelRef.current
if (sentinel == null || !hasNextPage || isFetching) return
const observer = new IntersectionObserver(([entry]) => {
if (entry?.isIntersecting) fetchNextPage()
})
observer.observe(sentinel)
return () => observer.disconnect()
}, [hasNextPage, isFetching, fetchNextPage])
if (isPending) return 'Loading...'
if (isError) return <span>Error: {error.message}</span>
return (
<>
<ul>
{data.pages.map((page) =>
page.projects.map((project) => <li key={project.id}>{project.name}</li>),
)}
</ul>
<div ref={sentinelRef}>{isFetchingNextPage ? 'Loading more...' : null}</div>
</>
)
}
```
## Call Signature
```ts
function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options, queryClient?): UseInfiniteQueryResult<TData, TError>;
```
Defined in: [packages/preact-query/src/useInfiniteQuery.ts:347](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useInfiniteQuery.ts#L347)
The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
`initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
### 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
[`UseInfiniteQueryOptions`](../interfaces/UseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
The [UseInfiniteQueryOptions](../interfaces/UseInfiniteQueryOptions.md) to use — everything you can pass to `useInfiniteQuery`.
#### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
### Returns
[`UseInfiniteQueryResult`](../type-aliases/UseInfiniteQueryResult.md)\<`TData`, `TError`\>
The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
`hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
`data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
`InfiniteData<TQueryFnData>` shape.
### Remarks
Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
actions, or add conditions like `hasNextPage && !isFetching`.
### See
[infiniteQueryOptions](infiniteQueryOptions.md) to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
### Examples
Fetching the next page from a "Load More" button click:
```tsx
import { useInfiniteQuery } from '@tanstack/preact-query'
function Projects() {
const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
useInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
})
if (isPending) return 'Loading...'
if (isError) return <span>Error: {error.message}</span>
return (
<>
<ul>
{data.pages.map((page) =>
page.projects.map((project) => <li key={project.id}>{project.name}</li>),
)}
</ul>
<button
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetching}
>
{isFetchingNextPage
? 'Loading more...'
: hasNextPage
? 'Load More'
: 'Nothing more to load'}
</button>
</>
)
}
```
Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
sentinel element after the list:
```tsx
import { useInfiniteQuery } from '@tanstack/preact-query'
import { useEffect, useRef } from 'preact/hooks'
function Projects() {
const {
data,
isPending,
isError,
error,
fetchNextPage,
hasNextPage,
isFetching,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
})
const sentinelRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const sentinel = sentinelRef.current
if (sentinel == null || !hasNextPage || isFetching) return
const observer = new IntersectionObserver(([entry]) => {
if (entry?.isIntersecting) fetchNextPage()
})
observer.observe(sentinel)
return () => observer.disconnect()
}, [hasNextPage, isFetching, fetchNextPage])
if (isPending) return 'Loading...'
if (isError) return <span>Error: {error.message}</span>
return (
<>
<ul>
{data.pages.map((page) =>
page.projects.map((project) => <li key={project.id}>{project.name}</li>),
)}
</ul>
<div ref={sentinelRef}>{isFetchingNextPage ? 'Loading more...' : null}</div>
</>
)
}
```
A query that's disabled, type safe, until `postId` is set — pass `skipToken` as `queryFn`
instead of setting `enabled: false`:
```tsx
import { skipToken, useInfiniteQuery } from '@tanstack/preact-query'
function Comments({ postId }: { postId: string | undefined }) {
// Use `isLoading`, not `isPending`, so the loading state doesn't show while the query is disabled.
const { data, isLoading, isError, error } = useInfiniteQuery({
queryKey: ['post', postId, 'comments'],
queryFn:
postId != null
? ({ pageParam }) => fetchComments(postId, pageParam)
: skipToken,
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
})
if (postId == null) return 'Select a post'
if (isLoading) return 'Loading...'
if (isError) return <span>Error: {error.message}</span>
return (
<ul>
{data?.pages.map((page) => page.comments.map((c) => <li key={c.id}>{c.text}</li>))}
</ul>
)
}
```

View File

@@ -0,0 +1,61 @@
---
id: useIsFetching
title: useIsFetching
---
```ts
function useIsFetching(filters?, queryClient?): number;
```
Defined in: [packages/preact-query/src/useIsFetching.ts:44](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useIsFetching.ts#L44)
The `useIsFetching` hook returns the `number` of the queries that your application is loading or fetching in
the background (useful for app-wide loading indicators).
## Parameters
### filters?
[`QueryFilters`](../interfaces/QueryFilters.md)\<readonly `unknown`[]\>
The [QueryFilters](../interfaces/QueryFilters.md) to narrow down the matched queries.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
## Returns
`number`
Will be the `number` of the queries that your application is currently loading or fetching in the
background.
## Examples
```tsx
import { useIsFetching } from '@tanstack/preact-query'
function PostsFetchingIndicator() {
// How many queries matching the posts prefix are fetching?
const isFetchingPosts = useIsFetching({ queryKey: ['posts'] })
return isFetchingPosts ? <span>Refreshing posts...</span> : null
}
```
A global loading indicator for any query fetching in the background, not just the ones on screen:
```tsx
import { useIsFetching } from '@tanstack/preact-query'
function GlobalLoadingIndicator() {
const isFetching = useIsFetching()
return isFetching ? (
<div>Queries are fetching in the background...</div>
) : null
}
```

View File

@@ -0,0 +1,47 @@
---
id: useIsMutating
title: useIsMutating
---
```ts
function useIsMutating(filters?, queryClient?): number;
```
Defined in: [packages/preact-query/src/useMutationState.ts:35](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useMutationState.ts#L35)
The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`
(useful for app-wide loading indicators).
## Parameters
### filters?
[`MutationFilters`](../interfaces/MutationFilters.md)\<`unknown`, `Error`, `unknown`, `unknown`\>
The [MutationFilters](../interfaces/MutationFilters.md) to narrow down the matched mutations.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
## Returns
`number`
Will be the `number` of the mutations that your application currently has `pending`.
## Example
```tsx
import { useIsMutating } from '@tanstack/preact-query'
function PostsMutatingIndicator() {
// How many mutations matching the posts prefix are in progress?
const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
return isMutatingPosts ? <span>Saving posts...</span> : null
}
```

View File

@@ -0,0 +1,20 @@
---
id: useIsRestoring
title: useIsRestoring
---
```ts
function useIsRestoring(): boolean;
```
Defined in: [packages/preact-query/src/IsRestoringProvider.ts:13](https://github.com/TanStack/query/blob/main/packages/preact-query/src/IsRestoringProvider.ts#L13)
If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to
check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid
race conditions between the restore and mounting queries.
## Returns
`boolean`
`true` while a persisted client is being restored, `false` otherwise.

View File

@@ -0,0 +1,215 @@
---
id: useMutation
title: useMutation
---
```ts
function useMutation<TData, TError, TVariables, TOnMutateResult>(options, queryClient?): UseMutationResult<TData, TError, TVariables, TOnMutateResult>;
```
Defined in: [packages/preact-query/src/useMutation.ts:192](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useMutation.ts#L192)
Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
`useMutation` is the hook for that.
## Type Parameters
### TData
`TData` = `unknown`
### TError
`TError` = `Error`
### TVariables
`TVariables` = `void`
### TOnMutateResult
`TOnMutateResult` = `unknown`
## Parameters
### options
[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
The [UseMutationOptions](../interfaces/UseMutationOptions.md) to use — everything you can pass to `useMutation`.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
## Returns
[`UseMutationResult`](../type-aliases/UseMutationResult.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
`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. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
fire only for the latest call you've made, and only while the component is still mounted — unmounting before
the mutation settles removes the subscription and prevents them from firing.
## See
[mutationOptions](mutationOptions.md) to share these options across multiple `useMutation` call sites, or to look
the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).
## Examples
```tsx
import { useMutation, useQueryClient } from '@tanstack/preact-query'
function AddTodo() {
const queryClient = useQueryClient()
const addMutation = useMutation({
mutationFn: addTodo,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
})
return (
<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:
```tsx
import { useMutation, useQueryClient } from '@tanstack/preact-query'
function AddTodo() {
const queryClient = useQueryClient()
const addMutation = useMutation({
mutationFn: addTodo,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
})
return (
<div>
{addMutation.isPending ? (
'Adding todo...'
) : (
<>
{addMutation.isError ? (
<div>An error occurred: {addMutation.error.message}</div>
) : null}
<button onClick={() => addMutation.mutate('Item')}>Add</button>
</>
)}
</div>
)
}
```
Optimistic update via `onMutate`, rolling back on `onError`:
```tsx
import { useMutation, useQueryClient } from '@tanstack/preact-query'
function AddTodo() {
const queryClient = useQueryClient()
const addMutation = useMutation({
mutationFn: addTodo,
onMutate: async (newTodo) => {
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'] })
},
})
return (
<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:
```tsx
import { useMutation, useQueryClient } from '@tanstack/preact-query'
function AddTodos() {
const queryClient = useQueryClient()
const addMutation = useMutation({
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)
}
}
return (
<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`:
```tsx
import { useMutation, useQueryClient } from '@tanstack/preact-query'
function AddTodos() {
const queryClient = useQueryClient()
const addMutation = useMutation({
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)
}
})
}
return (
<button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
Add all
</button>
)
}
```

View File

@@ -0,0 +1,107 @@
---
id: useMutationState
title: useMutationState
---
```ts
function useMutationState<TResult, TMutation>(options, queryClient?): TResult[];
```
Defined in: [packages/preact-query/src/useMutationState.ts:157](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useMutationState.ts#L157)
`useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass
`filters` ([MutationFilters](../interfaces/MutationFilters.md)) to narrow down your mutations, and `select` to transform the mutation
state.
## Type Parameters
### TResult
`TResult` = [`MutationState`](../interfaces/MutationState.md)\<`unknown`, `Error`, `unknown`, `unknown`\>
### TMutation
`TMutation` *extends* [`Mutation`](../classes/Mutation.md)\<`any`, `any`, `any`, `any`\> = `MutationTypeFromResult`\<`TResult`\>
## Parameters
### options
`MutationStateOptions`\<`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`[]
Will be an Array of whatever `select` returns for each matching mutation.
## Examples
Get all variables of all running mutations:
```tsx
import { useMutationState } from '@tanstack/preact-query'
function PendingPosts() {
const pendingVariables = useMutationState({
filters: { status: 'pending' },
select: (mutation) => mutation.state.variables,
})
return <>{pendingVariables.length} posts saving...</>
}
```
Get all data for specific mutations via the `mutationKey`:
```tsx
import { useMutation, useMutationState } from '@tanstack/preact-query'
const mutationKey = ['posts']
function Posts() {
// Some mutation that we want to get the state for
const mutation = useMutation({
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,
})
return (
<button onClick={() => mutation.mutate(['New Post'])}>
Create post ({savedPosts.length} saved so far)
</button>
)
}
```
Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the
last item that `useMutationState` returns to get the latest successful invocation:
```tsx
import { useMutationState } from '@tanstack/preact-query'
function LatestPost() {
const savedPosts = useMutationState({
filters: { mutationKey: ['posts'], status: 'success' },
select: (mutation) => mutation.state.data,
})
const latestSavedPost = savedPosts[savedPosts.length - 1]
return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>
}
```

View File

@@ -0,0 +1,92 @@
---
id: usePrefetchInfiniteQuery
title: usePrefetchInfiniteQuery
---
```ts
function usePrefetchInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options, queryClient?): void;
```
Defined in: [packages/preact-query/src/usePrefetchInfiniteQuery.tsx:51](https://github.com/TanStack/query/blob/main/packages/preact-query/src/usePrefetchInfiniteQuery.tsx#L51)
`usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render,
before a suspense boundary that wraps a component that uses `useSuspenseInfiniteQuery`. You can pass
everything to `usePrefetchInfiniteQuery` that you can pass to `queryClient.infiniteQuery`, though
`queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required unless
a default query function has been defined.
`getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages,
as well as pageParam information, and should return a single variable that will be passed to your query
function as `context.pageParam`. Return `undefined` or `null` to indicate there is no next page available.
The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left
over from a previous attempt — so calling this on every render is cheap and won't refetch data that's
already there or already in flight.
## Type Parameters
### TQueryFnData
`TQueryFnData` = `unknown`
### TError
`TError` = `Error`
### TData
`TData` = `TQueryFnData`
### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
### TPageParam
`TPageParam` = `unknown`
## Parameters
### options
[`UsePrefetchInfiniteQueryOptions`](../type-aliases/UsePrefetchInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
The [UsePrefetchInfiniteQueryOptions](../type-aliases/UsePrefetchInfiniteQueryOptions.md) to use — everything you can pass to `queryClient.infiniteQuery`.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
## Returns
`void`
`void` — nothing is returned.
## Example
```tsx
import { Suspense } from 'preact/compat'
import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/preact-query'
const projectsOptions = infiniteQueryOptions({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
})
function App() {
// Fire the prefetch during render, before the suspense boundary below.
usePrefetchInfiniteQuery(projectsOptions)
return (
<Suspense fallback={<h1>Loading projects...</h1>}>
<Projects />
</Suspense>
)
}
```

View File

@@ -0,0 +1,83 @@
---
id: usePrefetchQuery
title: usePrefetchQuery
---
```ts
function usePrefetchQuery<TQueryFnData, TError, TData, TQueryData, TQueryKey>(options, queryClient?): void;
```
Defined in: [packages/preact-query/src/usePrefetchQuery.tsx:42](https://github.com/TanStack/query/blob/main/packages/preact-query/src/usePrefetchQuery.tsx#L42)
`usePrefetchQuery` does not return anything, it should be used just to fire a prefetch during render, before
a suspense boundary that wraps a component that uses `useSuspenseQuery`. You can pass everything to
`usePrefetchQuery` that you can pass to `queryClient.query`, though `queryKey` is always required, and
`queryFn` is required unless a default query function has been defined.
The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left
over from a previous attempt — so calling this on every render is cheap and won't refetch data that's
already there or already in flight.
## Type Parameters
### TQueryFnData
`TQueryFnData` = `unknown`
### TError
`TError` = `Error`
### TData
`TData` = `TQueryFnData`
### TQueryData
`TQueryData` = `TQueryFnData`
### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
## Parameters
### options
[`UsePrefetchQueryOptions`](../type-aliases/UsePrefetchQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>
The [UsePrefetchQueryOptions](../type-aliases/UsePrefetchQueryOptions.md) to use — everything you can pass to `queryClient.query`.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
## Returns
`void`
`void` — nothing is returned.
## Example
```tsx
import { Suspense } from 'preact/compat'
import { usePrefetchQuery } from '@tanstack/preact-query'
function App() {
// Fire the prefetch during render, before the suspense boundary below.
usePrefetchQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
})
return (
<Suspense fallback={<h1>Loading posts...</h1>}>
<Posts />
</Suspense>
)
}
```

View File

@@ -0,0 +1,138 @@
---
id: useQueries
title: useQueries
---
```ts
function useQueries<T, TCombinedResult>(__namedParameters, queryClient?): TCombinedResult;
```
Defined in: [packages/preact-query/src/useQueries.ts:302](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useQueries.ts#L302)
The `useQueries` hook can be used to fetch a variable number of queries.
The `queries` key accepts an array with query option objects mostly identical to `useQuery` — see the
`queries` parameter below for the differences. A custom `QueryClient` is supplied once, as `useQueries`' own
top-level second argument, rather than per query.
Having the same query key more than once in the array of query objects may cause some data to be shared
between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
structure.
The `combine` option can be used to combine the results of the queries into a single value. The result will
be structurally shared to be as referentially stable as possible.
## Type Parameters
### T
`T` *extends* `any`[]
### TCombinedResult
`TCombinedResult` = `T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseQueryResult`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseQueryResult`\<`Head`\>, `GetUseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseQueryResult`\<`Head`\>, `GetUseQueryResult`\<`Head`\>, `GetUseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : \[`...{ [K in (...)]: (...) }[]`\] : \[...\{ \[K in string \| number \| symbol\]: GetUseQueryResult\<Tails\[K\<(...)\>\]\> \}\[\]\] : \{ \[K in string \| number \| symbol\]: GetUseQueryResult\<T\[K\<K\>\]\> \}
## Parameters
### \_\_namedParameters
#### combine?
(`result`) => `TCombinedResult`
Use this to combine the results of the queries into a single value. The result will be structurally
shared to be as referentially stable as possible.
#### queries
\| readonly \[`T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseQueryOptionsForUseQueries`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseQueryOptionsForUseQueries`\<`Head`\>, `GetUseQueryOptionsForUseQueries`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : readonly ...[] *extends* \[`...(...)[]`\] ? \[`...(...)[]`\] : ... *extends* ... ? ... : ... : readonly `unknown`[] *extends* `T` ? `T` : `T` *extends* `UseQueryOptionsForUseQueries`\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] ? `UseQueryOptionsForUseQueries`\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] : `UseQueryOptionsForUseQueries`\<`unknown`, `Error`, `unknown`, readonly ...[]\>[]\]
\| readonly \[\{ \[K in string \| number \| symbol\]: GetUseQueryOptionsForUseQueries\<T\[K\<K\>\]\> \}\]
An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and
`subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and
`placeholderData` accepts a [QueriesPlaceholderDataFunction](../type-aliases/QueriesPlaceholderDataFunction.md), which is called with `previousData`
and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.
#### subscribed?
`boolean`
Set this to `false` to unsubscribe this observer from updates to the query cache.
**Default Value**
```ts
true
```
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
will be used.
## Returns
`TCombinedResult`
The combined result. Without `combine`, this is an array with all the query results, in the same
order as the input. When `combine` is provided, this is the value returned by `combine` instead.
## Examples
```tsx
import { useQueries } from '@tanstack/preact-query'
function Posts({ ids }: { ids: Array<number> }) {
const postQueries = useQueries({
queries: ids.map((id) => ({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
staleTime: Infinity,
})),
})
return (
<ul>
{postQueries.map((query, index) => {
if (query.isPending) return <li key={ids[index]}>Loading...</li>
if (query.isError) return <li key={ids[index]}>Error: {query.error.message}</li>
return <li key={ids[index]}>{query.data.title}</li>
})}
</ul>
)
}
```
Combining results into a single value:
```tsx
import { useQueries } from '@tanstack/preact-query'
function Posts({ ids }: { ids: Array<number> }) {
const { data, isPending, isError } = useQueries({
queries: ids.map((id) => ({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
})),
combine: (postQueries) => {
return {
data: postQueries.map((query) => query.data),
isPending: postQueries.some((query) => query.isPending),
isError: postQueries.some((query) => query.isError),
}
},
})
if (isPending) return 'Loading...'
if (isError) return 'Error loading posts'
return (
<ul>
{data.map((post) => (
<li key={post?.id}>{post?.title}</li>
))}
</ul>
)
}
```

View File

@@ -0,0 +1,379 @@
---
id: useQuery
title: useQuery
---
## Call Signature
```ts
function useQuery<TQueryFnData, TError, TData, TQueryKey>(options, queryClient?): DefinedUseQueryResult<TData, TError>;
```
Defined in: [packages/preact-query/src/useQuery.ts:50](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useQuery.ts#L50)
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 `useQuery`, with `initialData` set.
#### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
### Returns
[`DefinedUseQueryResult`](../type-aliases/DefinedUseQueryResult.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 `useQuery` and imperative APIs like `queryClient.query`.
### Example
```tsx
import { useQuery } from '@tanstack/preact-query'
function Posts() {
// `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails,
// so the list stays visible alongside the error.
const { data, isError, error } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
initialData: [],
})
return (
<div>
{isError ? <span>Error: {error.message}</span> : null}
<ul>
{data.map((post) => <li key={post.id}>{post.title}</li>)}
</ul>
</div>
)
}
```
## Call Signature
```ts
function useQuery<TQueryFnData, TError, TData, TQueryKey>(options, queryClient?): UseQueryResult<TData, TError>;
```
Defined in: [packages/preact-query/src/useQuery.ts:117](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useQuery.ts#L117)
### 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 `useQuery`.
#### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
### Returns
[`UseQueryResult`](../type-aliases/UseQueryResult.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 `useQuery` and imperative APIs like `queryClient.query`.
### Examples
```tsx
import { useQuery } from '@tanstack/preact-query'
function Posts() {
const { status, data, error, isFetching } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
})
if (status === 'pending') return 'Loading...'
if (status === 'error') return <span>Error: {error.message}</span>
return (
<div>
<ul>
{data.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
<div>{isFetching ? 'Background Updating...' : ' '}</div>
</div>
)
}
```
The same query, checking `isPending`/`isError` instead of `status` — pick whichever reads better to you:
```tsx
import { useQuery } from '@tanstack/preact-query'
function Posts() {
const { isPending, isError, data, error } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
})
if (isPending) return 'Loading...'
if (isError) return <span>Error: {error.message}</span>
return (
<ul>
{data.map((post) => <li key={post.id}>{post.title}</li>)}
</ul>
)
}
```
## Call Signature
```ts
function useQuery<TQueryFnData, TError, TData, TQueryKey>(options, queryClient?): UseQueryResult<TData, TError>;
```
Defined in: [packages/preact-query/src/useQuery.ts:281](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useQuery.ts#L281)
### Type Parameters
#### TQueryFnData
`TQueryFnData` = `unknown`
#### TError
`TError` = `Error`
#### TData
`TData` = `TQueryFnData`
#### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
### Parameters
#### options
[`UseQueryOptions`](../interfaces/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
The [UseQueryOptions](../interfaces/UseQueryOptions.md) to use — everything you can pass to `useQuery`.
#### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
### Returns
[`UseQueryResult`](../type-aliases/UseQueryResult.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 `useQuery` and imperative APIs like `queryClient.query`.
### Examples
```tsx
import { useQuery } from '@tanstack/preact-query'
function Posts() {
const { status, data, error, isFetching } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
})
if (status === 'pending') return 'Loading...'
if (status === 'error') return <span>Error: {error.message}</span>
return (
<div>
<ul>
{data.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
<div>{isFetching ? 'Background Updating...' : ' '}</div>
</div>
)
}
```
`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`:
```tsx
import { useQuery } from '@tanstack/preact-query'
function PostCount() {
const { data, isPending, isError, error } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
select: (posts) => posts.length,
})
if (isPending) return 'Loading...'
if (isError) return <span>Error: {error.message}</span>
return <span>{data} posts</span>
}
```
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:
```tsx
import { useQuery } from '@tanstack/preact-query'
function Post({ postId }: { postId: number | undefined }) {
const { data, isLoading, isError, error } = useQuery({
queryKey: ['post', postId],
queryFn: () => fetchPost(postId!),
enabled: postId != null,
})
if (postId == null) return 'Select a post'
if (isLoading) return 'Loading...'
if (isError) return <span>Error: {error.message}</span>
return <h1>{data?.title}</h1>
}
```
The same dependent query, type safe: `skipToken` disables the query without needing the
non-null assertion above, since `queryFn` is only ever called when `postId` is defined.
`refetch` doesn't work while `queryFn` is `skipToken` — use `enabled: false` instead if you
need to trigger the query manually:
```tsx
import { skipToken, useQuery } from '@tanstack/preact-query'
function Post({ postId }: { postId: number | undefined }) {
const { data, isLoading, isError, error } = useQuery({
queryKey: ['post', postId],
queryFn: postId != null ? () => fetchPost(postId) : skipToken,
})
if (postId == null) return 'Select a post'
if (isLoading) return 'Loading...'
if (isError) return <span>Error: {error.message}</span>
return <h1>{data?.title}</h1>
}
```
Seeding a detail query from an already-cached list, to skip the loading state:
```tsx
import { useQuery, useQueryClient } from '@tanstack/preact-query'
function Post({ postId }: { postId: number }) {
const queryClient = useQueryClient()
const { data, isError, error } = useQuery({
queryKey: ['post', postId],
queryFn: () => fetchPost(postId),
initialData: () =>
queryClient
.getQueryData<Array<Post>>(['posts'])
?.find((post) => post.id === postId),
})
if (isError) return <span>Error: {error.message}</span>
return <h1>{data?.title}</h1>
}
```
Paginated data, keeping the previous page's data visible while the next page loads:
```tsx
import { keepPreviousData, useQuery } from '@tanstack/preact-query'
import { useState } from 'preact/hooks'
function Posts() {
const [page, setPage] = useState(0)
const { data, isPlaceholderData, isError, error } = useQuery({
queryKey: ['posts', page],
queryFn: () => fetchPosts(page),
placeholderData: keepPreviousData,
})
if (isError) return <span>Error: {error.message}</span>
return (
<div>
<ul>
{data?.map((post) => <li key={post.id}>{post.title}</li>)}
</ul>
<button
disabled={isPlaceholderData}
onClick={() => setPage((old) => old + 1)}
>
Next Page
</button>
</div>
)
}
```

View File

@@ -0,0 +1,31 @@
---
id: useQueryClient
title: useQueryClient
---
```ts
function useQueryClient(queryClient?): QueryClient;
```
Defined in: [packages/preact-query/src/QueryClientProvider.tsx:21](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryClientProvider.tsx#L21)
The `useQueryClient` hook returns the current `QueryClient` instance.
## Parameters
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
## Returns
[`QueryClient`](../classes/QueryClient.md)
The current `QueryClient` instance.
## Throws
If no `queryClient` argument is passed and no `QueryClientProvider` is found in the component tree.

View File

@@ -0,0 +1,43 @@
---
id: useQueryErrorResetBoundary
title: useQueryErrorResetBoundary
---
```ts
function useQueryErrorResetBoundary(): QueryErrorResetBoundaryValue;
```
Defined in: [packages/preact-query/src/QueryErrorResetBoundary.tsx:85](https://github.com/TanStack/query/blob/main/packages/preact-query/src/QueryErrorResetBoundary.tsx#L85)
This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary
defined it will reset them globally.
## Returns
`QueryErrorResetBoundaryValue`
The boundary's QueryErrorResetBoundaryValue.
## Example
```tsx
import { useErrorBoundary } from 'preact/hooks'
import type { ComponentChildren } from 'preact'
import { useQueryErrorResetBoundary } from '@tanstack/preact-query'
function App({ children }: { children: ComponentChildren }) {
const { reset } = useQueryErrorResetBoundary()
const [error, resetError] = useErrorBoundary(() => reset())
if (error) {
return (
<div>
There was an error!
<button onClick={() => resetError()}>Try again</button>
</div>
)
}
return children
}
```

View File

@@ -0,0 +1,160 @@
---
id: useSuspenseInfiniteQuery
title: useSuspenseInfiniteQuery
---
```ts
function useSuspenseInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options, queryClient?): UseSuspenseInfiniteQueryResult<TData, TError>;
```
Defined in: [packages/preact-query/src/useSuspenseInfiniteQuery.ts:124](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useSuspenseInfiniteQuery.ts#L124)
The options for `useSuspenseInfiniteQuery` are the same as for `useInfiniteQuery`, except for `throwOnError`,
`enabled`, and `placeholderData`.
Caveat: cancellation does not work.
## 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
[`UseSuspenseInfiniteQueryOptions`](../interfaces/UseSuspenseInfiniteQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
The [UseSuspenseInfiniteQueryOptions](../interfaces/UseSuspenseInfiniteQueryOptions.md) to use — the same options as `useInfiniteQuery`, minus the ones listed above.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
## Returns
[`UseSuspenseInfiniteQueryResult`](../type-aliases/UseSuspenseInfiniteQueryResult.md)\<`TData`, `TError`\>
The same object as `useInfiniteQuery`, except that `data` is guaranteed to be defined,
`isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived flags set
accordingly).
## Remarks
Multiple suspenseful query calls in the same component suspend serially, causing a request
waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until
then. There's no way to parallelize multiple infinite queries under Suspense. Also keep in mind that
imperative fetch calls, such as `fetchNextPage`, may interfere with the default refetch behavior,
resulting in outdated data. Make sure to call these functions only in response to user actions, or add
conditions like `hasNextPage && !isFetching`.
## See
[useInfiniteQuery](useInfiniteQuery.md) for the non-Suspense version of this hook.
## Example
The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is
required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
Use [QueryErrorResetBoundary](QueryErrorResetBoundary.md) to let the user retry after such an error:
```tsx
import { Suspense } from 'preact/compat'
import { useErrorBoundary } from 'preact/hooks'
import {
QueryErrorResetBoundary,
useSuspenseInfiniteQuery,
} from '@tanstack/preact-query'
import type { ComponentChildren } from 'preact'
function Projects() {
// `data` is guaranteed to be defined here — no `isPending` check needed.
const { data, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
useSuspenseInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextId,
})
return (
<div>
<ul>
{data.pages.map((page) =>
page.projects.map((project) => <li key={project.id}>{project.name}</li>),
)}
</ul>
<button
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetching}
>
{isFetchingNextPage
? 'Loading more...'
: hasNextPage
? 'Load More'
: 'Nothing more to load'}
</button>
</div>
)
}
function App() {
return (
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
There was an error!
<button onClick={() => resetErrorBoundary()}>Try again</button>
</div>
)}
>
<Suspense fallback={<h1>Loading projects...</h1>}>
<Projects />
</Suspense>
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
)
}
function ErrorBoundary({
children,
onReset,
fallbackRender,
}: {
children: ComponentChildren
onReset: () => void
fallbackRender: (props: {
error: Error
resetErrorBoundary: () => void
}) => ComponentChildren
}) {
const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
if (error) return fallbackRender({ error, resetErrorBoundary })
return children
}
```

View File

@@ -0,0 +1,478 @@
---
id: useSuspenseQueries
title: useSuspenseQueries
---
## Call Signature
```ts
function useSuspenseQueries<T, TCombinedResult>(options, queryClient?): TCombinedResult;
```
Defined in: [packages/preact-query/src/useSuspenseQueries.ts:409](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useSuspenseQueries.ts#L409)
The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed`
option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`.
### Type Parameters
#### T
`T` *extends* `any`[]
#### TCombinedResult
`TCombinedResult` = `T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>, `GetUseSuspenseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>, `GetUseSuspenseQueryResult`\<`Head`\>, `GetUseSuspenseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : \[`...{ [K in (...)]: (...) }[]`\] : \[...\{ \[K in string \| number \| symbol\]: GetUseSuspenseQueryResult\<Tails\[K\<(...)\>\]\> \}\[\]\] : \{ \[K in string \| number \| symbol\]: GetUseSuspenseQueryResult\<T\[K\<K\>\]\> \}
### Parameters
#### options
The `queries` array to run in Suspense, and an optional `combine` function.
##### combine?
(`result`) => `TCombinedResult`
Use this to combine the results of the queries into a single value. The result will be structurally
shared to be as referentially stable as possible.
##### queries
\| readonly \[`T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseSuspenseQueryOptions`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryOptions`\<`Head`\>, `GetUseSuspenseQueryOptions`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : ...[] *extends* \[`...(...)[]`\] ? \[`...(...)[]`\] : ... *extends* ... ? ... : ... : `unknown`[] *extends* `T` ? `T` : `T` *extends* [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] ? [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] : [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`unknown`, `Error`, `unknown`, readonly ...[]\>[]\]
\| readonly \[\{ \[K in string \| number \| symbol\]: GetUseSuspenseQueryOptions\<T\[K\<K\>\]\> \}\]
An array with query option objects identical to `useSuspenseQuery`.
#### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
will be used.
### Returns
`TCombinedResult`
The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be
defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived
flags set accordingly).
Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone
stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid
this, make sure to set a high enough `staleTime`. Cancellation does not work.
### Examples
The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is
required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
Use [QueryErrorResetBoundary](QueryErrorResetBoundary.md) to let the user retry after such an error:
```tsx
import { Suspense } from 'preact/compat'
import { useErrorBoundary } from 'preact/hooks'
import {
QueryErrorResetBoundary,
useSuspenseQueries,
} from '@tanstack/preact-query'
import type { ComponentChildren } from 'preact'
function Posts({ ids }: { ids: Array<number> }) {
// Every result is guaranteed to be defined — no per-query `isPending` check needed.
const postQueries = useSuspenseQueries({
queries: ids.map((id) => ({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
})),
})
return (
<ul>
{postQueries.map((query) => (
<li key={query.data.id}>{query.data.title}</li>
))}
</ul>
)
}
function App() {
return (
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
There was an error!
<button onClick={() => resetErrorBoundary()}>Try again</button>
</div>
)}
>
<Suspense fallback={<h1>Loading posts...</h1>}>
<Posts ids={[1, 2, 3]} />
</Suspense>
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
)
}
function ErrorBoundary({
children,
onReset,
fallbackRender,
}: {
children: ComponentChildren
onReset: () => void
fallbackRender: (props: {
error: Error
resetErrorBoundary: () => void
}) => ComponentChildren
}) {
const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
if (error) return fallbackRender({ error, resetErrorBoundary })
return children
}
```
Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so
they fetch in parallel rather than suspending one after another:
```tsx
import { Suspense } from 'preact/compat'
import { useErrorBoundary } from 'preact/hooks'
import {
QueryErrorResetBoundary,
useSuspenseQueries,
} from '@tanstack/preact-query'
import type { ComponentChildren } from 'preact'
function Dashboard() {
const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({
queries: [
{ queryKey: ['users'], queryFn: fetchUsers },
{ queryKey: ['teams'], queryFn: fetchTeams },
{ queryKey: ['projects'], queryFn: fetchProjects },
],
})
return (
<div>
<UserList users={usersQuery.data} />
<TeamList teams={teamsQuery.data} />
<ProjectList projects={projectsQuery.data} />
</div>
)
}
function App() {
return (
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
There was an error!
<button onClick={() => resetErrorBoundary()}>Try again</button>
</div>
)}
>
<Suspense fallback={<h1>Loading dashboard...</h1>}>
<Dashboard />
</Suspense>
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
)
}
function ErrorBoundary({
children,
onReset,
fallbackRender,
}: {
children: ComponentChildren
onReset: () => void
fallbackRender: (props: {
error: Error
resetErrorBoundary: () => void
}) => ComponentChildren
}) {
const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
if (error) return fallbackRender({ error, resetErrorBoundary })
return children
}
```
`combine`s the results into a single boolean, so `Refresh` only re-renders when that boolean changes,
not on every individual query update. This overload is the only one that accepts `combine`:
```tsx
import { Suspense } from 'preact/compat'
import { useErrorBoundary } from 'preact/hooks'
import {
QueryErrorResetBoundary,
useSuspenseQueries,
} from '@tanstack/preact-query'
import type { ComponentChildren } from 'preact'
function Refresh() {
const anyFetching = useSuspenseQueries({
queries: [
{ queryKey: ['users'], queryFn: fetchUsers },
{ queryKey: ['teams'], queryFn: fetchTeams },
],
combine: (results) => results.some((result) => result.isFetching),
})
return anyFetching ? <span>Refreshing…</span> : null
}
function App() {
return (
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
There was an error!
<button onClick={() => resetErrorBoundary()}>Try again</button>
</div>
)}
>
<Suspense fallback={<h1>Loading dashboard...</h1>}>
<Refresh />
</Suspense>
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
)
}
function ErrorBoundary({
children,
onReset,
fallbackRender,
}: {
children: ComponentChildren
onReset: () => void
fallbackRender: (props: {
error: Error
resetErrorBoundary: () => void
}) => ComponentChildren
}) {
const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
if (error) return fallbackRender({ error, resetErrorBoundary })
return children
}
```
## Call Signature
```ts
function useSuspenseQueries<T, TCombinedResult>(options, queryClient?): TCombinedResult;
```
Defined in: [packages/preact-query/src/useSuspenseQueries.ts:589](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useSuspenseQueries.ts#L589)
The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed`
option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`.
### Type Parameters
#### T
`T` *extends* `any`[]
#### TCombinedResult
`TCombinedResult` = `T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>, `GetUseSuspenseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryResult`\<`Head`\>, `GetUseSuspenseQueryResult`\<`Head`\>, `GetUseSuspenseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : \[`...{ [K in (...)]: (...) }[]`\] : \[...\{ \[K in string \| number \| symbol\]: GetUseSuspenseQueryResult\<Tails\[K\<(...)\>\]\> \}\[\]\] : \{ \[K in string \| number \| symbol\]: GetUseSuspenseQueryResult\<T\[K\<K\>\]\> \}
### Parameters
#### options
The `queries` array to run in Suspense, and an optional `combine` function.
##### combine?
(`result`) => `TCombinedResult`
Use this to combine the results of the queries into a single value. The result will be structurally
shared to be as referentially stable as possible.
##### queries
readonly \[`T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseSuspenseQueryOptions`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseSuspenseQueryOptions`\<`Head`\>, `GetUseSuspenseQueryOptions`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...(...)[]`\] *extends* \[...\] ? \[..., ..., ...\] : ... *extends* ... ? ... : ... : `unknown`[] *extends* \[`...Tails[]`\] ? \[`...Tails[]`\] : \[`...(...)[]`\] *extends* ...[] ? ...[] : ...[] : `unknown`[] *extends* `T` ? `T` : `T` *extends* [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] ? [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] : [`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`unknown`, `Error`, `unknown`, readonly `unknown`[]\>[]\]
An array with query option objects identical to `useSuspenseQuery`.
#### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
will be used.
### Returns
`TCombinedResult`
The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be
defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived
flags set accordingly).
Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone
stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid
this, make sure to set a high enough `staleTime`. Cancellation does not work.
### Examples
The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is
required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
Use [QueryErrorResetBoundary](QueryErrorResetBoundary.md) to let the user retry after such an error:
```tsx
import { Suspense } from 'preact/compat'
import { useErrorBoundary } from 'preact/hooks'
import {
QueryErrorResetBoundary,
useSuspenseQueries,
} from '@tanstack/preact-query'
import type { ComponentChildren } from 'preact'
function Posts({ ids }: { ids: Array<number> }) {
// Every result is guaranteed to be defined — no per-query `isPending` check needed.
const postQueries = useSuspenseQueries({
queries: ids.map((id) => ({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
})),
})
return (
<ul>
{postQueries.map((query) => (
<li key={query.data.id}>{query.data.title}</li>
))}
</ul>
)
}
function App() {
return (
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
There was an error!
<button onClick={() => resetErrorBoundary()}>Try again</button>
</div>
)}
>
<Suspense fallback={<h1>Loading posts...</h1>}>
<Posts ids={[1, 2, 3]} />
</Suspense>
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
)
}
function ErrorBoundary({
children,
onReset,
fallbackRender,
}: {
children: ComponentChildren
onReset: () => void
fallbackRender: (props: {
error: Error
resetErrorBoundary: () => void
}) => ComponentChildren
}) {
const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
if (error) return fallbackRender({ error, resetErrorBoundary })
return children
}
```
Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so
they fetch in parallel rather than suspending one after another:
```tsx
import { Suspense } from 'preact/compat'
import { useErrorBoundary } from 'preact/hooks'
import {
QueryErrorResetBoundary,
useSuspenseQueries,
} from '@tanstack/preact-query'
import type { ComponentChildren } from 'preact'
function Dashboard() {
const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({
queries: [
{ queryKey: ['users'], queryFn: fetchUsers },
{ queryKey: ['teams'], queryFn: fetchTeams },
{ queryKey: ['projects'], queryFn: fetchProjects },
],
})
return (
<div>
<UserList users={usersQuery.data} />
<TeamList teams={teamsQuery.data} />
<ProjectList projects={projectsQuery.data} />
</div>
)
}
function App() {
return (
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
There was an error!
<button onClick={() => resetErrorBoundary()}>Try again</button>
</div>
)}
>
<Suspense fallback={<h1>Loading dashboard...</h1>}>
<Dashboard />
</Suspense>
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
)
}
function ErrorBoundary({
children,
onReset,
fallbackRender,
}: {
children: ComponentChildren
onReset: () => void
fallbackRender: (props: {
error: Error
resetErrorBoundary: () => void
}) => ComponentChildren
}) {
const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
if (error) return fallbackRender({ error, resetErrorBoundary })
return children
}
```

View File

@@ -0,0 +1,134 @@
---
id: useSuspenseQuery
title: useSuspenseQuery
---
```ts
function useSuspenseQuery<TQueryFnData, TError, TData, TQueryKey>(options, queryClient?): UseSuspenseQueryResult<TData, TError>;
```
Defined in: [packages/preact-query/src/useSuspenseQuery.ts:95](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useSuspenseQuery.ts#L95)
The options for `useSuspenseQuery` are the same as for `useQuery`, except for `throwOnError`, `enabled`, and
`placeholderData`.
Caveat: cancellation does not work.
## Type Parameters
### TQueryFnData
`TQueryFnData` = `unknown`
### TError
`TError` = `Error`
### TData
`TData` = `TQueryFnData`
### TQueryKey
`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
## Parameters
### options
[`UseSuspenseQueryOptions`](../interfaces/UseSuspenseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
The [UseSuspenseQueryOptions](../interfaces/UseSuspenseQueryOptions.md) to use — the same options as `useQuery`, minus the ones listed above.
### queryClient?
[`QueryClient`](../classes/QueryClient.md)
Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
be used.
## Returns
[`UseSuspenseQueryResult`](../type-aliases/UseSuspenseQueryResult.md)\<`TData`, `TError`\>
The same object as `useQuery`, except that `data` is guaranteed to be defined, `isPlaceholderData`
is missing, and `status` is either `success` or `error` (with the derived flags set accordingly).
## Remarks
Multiple `useSuspenseQuery` calls in the same component suspend serially, causing a request
waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until then.
Use [useSuspenseQueries](useSuspenseQueries.md) instead when you have more than one suspenseful query in a component, so they
fetch in parallel.
## Example
The query error is thrown if the fetch fails and no cached data exists yet, so an error boundary is
required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
Use [QueryErrorResetBoundary](QueryErrorResetBoundary.md) to let the user retry after such an error:
```tsx
import { Suspense } from 'preact/compat'
import { useErrorBoundary } from 'preact/hooks'
import { QueryErrorResetBoundary, useSuspenseQuery } from '@tanstack/preact-query'
import type { ComponentChildren } from 'preact'
function Posts() {
// `data` is guaranteed to be defined here — no `isPending` check needed.
const { data, isFetching } = useSuspenseQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
})
return (
<div>
<h1>Posts {isFetching ? '(refreshing...)' : null}</h1>
<ul>
{data.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
)
}
function App() {
return (
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
There was an error!
<button onClick={() => resetErrorBoundary()}>Try again</button>
</div>
)}
>
<Suspense fallback={<h1>Loading posts...</h1>}>
<Posts />
</Suspense>
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
)
}
function ErrorBoundary({
children,
onReset,
fallbackRender,
}: {
children: ComponentChildren
onReset: () => void
fallbackRender: (props: {
error: Error
resetErrorBoundary: () => void
}) => ComponentChildren
}) {
const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
if (error) return fallbackRender({ error, resetErrorBoundary })
return children
}
```

View File

@@ -0,0 +1,237 @@
---
id: "@tanstack/preact-query"
title: "@tanstack/preact-query"
---
## Classes
- [CancelledError](classes/CancelledError.md)
- [InfiniteQueryObserver](classes/InfiniteQueryObserver.md)
- [Mutation](classes/Mutation.md)
- [MutationCache](classes/MutationCache.md)
- [MutationObserver](classes/MutationObserver.md)
- [QueriesObserver](classes/QueriesObserver.md)
- [Query](classes/Query.md)
- [QueryCache](classes/QueryCache.md)
- [QueryClient](classes/QueryClient.md)
- [QueryObserver](classes/QueryObserver.md)
## Interfaces
- [CancelOptions](interfaces/CancelOptions.md)
- [DefaultOptions](interfaces/DefaultOptions.md)
- [DehydratedState](interfaces/DehydratedState.md)
- [DehydrateOptions](interfaces/DehydrateOptions.md)
- [~~EnsureQueryDataOptions~~](interfaces/EnsureQueryDataOptions.md)
- [FetchNextPageOptions](interfaces/FetchNextPageOptions.md)
- [FetchPreviousPageOptions](interfaces/FetchPreviousPageOptions.md)
- [~~FetchQueryOptions~~](interfaces/FetchQueryOptions.md)
- [FocusManager](interfaces/FocusManager.md)
- [HydrateOptions](interfaces/HydrateOptions.md)
- [HydrationBoundaryProps](interfaces/HydrationBoundaryProps.md)
- [InfiniteData](interfaces/InfiniteData.md)
- [InfiniteQueryObserverBaseResult](interfaces/InfiniteQueryObserverBaseResult.md)
- [InfiniteQueryObserverLoadingErrorResult](interfaces/InfiniteQueryObserverLoadingErrorResult.md)
- [InfiniteQueryObserverLoadingResult](interfaces/InfiniteQueryObserverLoadingResult.md)
- [InfiniteQueryObserverOptions](interfaces/InfiniteQueryObserverOptions.md)
- [InfiniteQueryObserverPendingResult](interfaces/InfiniteQueryObserverPendingResult.md)
- [InfiniteQueryObserverPlaceholderResult](interfaces/InfiniteQueryObserverPlaceholderResult.md)
- [InfiniteQueryObserverRefetchErrorResult](interfaces/InfiniteQueryObserverRefetchErrorResult.md)
- [InfiniteQueryObserverSuccessResult](interfaces/InfiniteQueryObserverSuccessResult.md)
- [InfiniteQueryPageParamsOptions](interfaces/InfiniteQueryPageParamsOptions.md)
- [InitialPageParam](interfaces/InitialPageParam.md)
- [InvalidateOptions](interfaces/InvalidateOptions.md)
- [InvalidateQueryFilters](interfaces/InvalidateQueryFilters.md)
- [MutateOptions](interfaces/MutateOptions.md)
- [MutationCacheConfig](interfaces/MutationCacheConfig.md)
- [MutationFilters](interfaces/MutationFilters.md)
- [MutationObserverBaseResult](interfaces/MutationObserverBaseResult.md)
- [MutationObserverErrorResult](interfaces/MutationObserverErrorResult.md)
- [MutationObserverIdleResult](interfaces/MutationObserverIdleResult.md)
- [MutationObserverLoadingResult](interfaces/MutationObserverLoadingResult.md)
- [MutationObserverOptions](interfaces/MutationObserverOptions.md)
- [MutationObserverSuccessResult](interfaces/MutationObserverSuccessResult.md)
- [MutationOptions](interfaces/MutationOptions.md)
- [MutationState](interfaces/MutationState.md)
- [NotifyEvent](interfaces/NotifyEvent.md)
- [OnlineManager](interfaces/OnlineManager.md)
- [QueriesObserverOptions](interfaces/QueriesObserverOptions.md)
- [QueryCacheConfig](interfaces/QueryCacheConfig.md)
- [QueryClientConfig](interfaces/QueryClientConfig.md)
- [QueryErrorResetBoundaryProps](interfaces/QueryErrorResetBoundaryProps.md)
- [QueryExecuteOptions](interfaces/QueryExecuteOptions.md)
- [QueryFilters](interfaces/QueryFilters.md)
- [QueryObserverBaseResult](interfaces/QueryObserverBaseResult.md)
- [QueryObserverLoadingErrorResult](interfaces/QueryObserverLoadingErrorResult.md)
- [QueryObserverLoadingResult](interfaces/QueryObserverLoadingResult.md)
- [QueryObserverOptions](interfaces/QueryObserverOptions.md)
- [QueryObserverPendingResult](interfaces/QueryObserverPendingResult.md)
- [QueryObserverPlaceholderResult](interfaces/QueryObserverPlaceholderResult.md)
- [QueryObserverRefetchErrorResult](interfaces/QueryObserverRefetchErrorResult.md)
- [QueryObserverSuccessResult](interfaces/QueryObserverSuccessResult.md)
- [QueryOptions](interfaces/QueryOptions.md)
- [QueryState](interfaces/QueryState.md)
- [RefetchOptions](interfaces/RefetchOptions.md)
- [RefetchQueryFilters](interfaces/RefetchQueryFilters.md)
- [Register](interfaces/Register.md)
- [ResetOptions](interfaces/ResetOptions.md)
- [ResultOptions](interfaces/ResultOptions.md)
- [SetDataOptions](interfaces/SetDataOptions.md)
- [TimeoutManager](interfaces/TimeoutManager.md)
- [UseBaseQueryOptions](interfaces/UseBaseQueryOptions.md)
- [UseInfiniteQueryOptions](interfaces/UseInfiniteQueryOptions.md)
- [UseMutationOptions](interfaces/UseMutationOptions.md)
- [UseQueryOptions](interfaces/UseQueryOptions.md)
- [UseSuspenseInfiniteQueryOptions](interfaces/UseSuspenseInfiniteQueryOptions.md)
- [UseSuspenseQueryOptions](interfaces/UseSuspenseQueryOptions.md)
## Type Aliases
- [AnyDataTag](type-aliases/AnyDataTag.md)
- [AnyUseBaseQueryOptions](type-aliases/AnyUseBaseQueryOptions.md)
- [AnyUseInfiniteQueryOptions](type-aliases/AnyUseInfiniteQueryOptions.md)
- [AnyUseMutationOptions](type-aliases/AnyUseMutationOptions.md)
- [AnyUseQueryOptions](type-aliases/AnyUseQueryOptions.md)
- [AnyUseSuspenseInfiniteQueryOptions](type-aliases/AnyUseSuspenseInfiniteQueryOptions.md)
- [AnyUseSuspenseQueryOptions](type-aliases/AnyUseSuspenseQueryOptions.md)
- [DataTag](type-aliases/DataTag.md)
- [dataTagErrorSymbol](type-aliases/dataTagErrorSymbol.md)
- [dataTagSymbol](type-aliases/dataTagSymbol.md)
- [DefaultedInfiniteQueryObserverOptions](type-aliases/DefaultedInfiniteQueryObserverOptions.md)
- [DefaultedQueryObserverOptions](type-aliases/DefaultedQueryObserverOptions.md)
- [DefaultError](type-aliases/DefaultError.md)
- [DefinedInfiniteQueryObserverResult](type-aliases/DefinedInfiniteQueryObserverResult.md)
- [DefinedInitialDataInfiniteOptions](type-aliases/DefinedInitialDataInfiniteOptions.md)
- [DefinedInitialDataOptions](type-aliases/DefinedInitialDataOptions.md)
- [DefinedQueryObserverResult](type-aliases/DefinedQueryObserverResult.md)
- [DefinedUseInfiniteQueryResult](type-aliases/DefinedUseInfiniteQueryResult.md)
- [DefinedUseQueryResult](type-aliases/DefinedUseQueryResult.md)
- [DistributiveOmit](type-aliases/DistributiveOmit.md)
- [~~EnsureInfiniteQueryDataOptions~~](type-aliases/EnsureInfiniteQueryDataOptions.md)
- [~~FetchInfiniteQueryOptions~~](type-aliases/FetchInfiniteQueryOptions.md)
- [FetchStatus](type-aliases/FetchStatus.md)
- [GetNextPageParamFunction](type-aliases/GetNextPageParamFunction.md)
- [GetPreviousPageParamFunction](type-aliases/GetPreviousPageParamFunction.md)
- [InferDataFromTag](type-aliases/InferDataFromTag.md)
- [InferErrorFromTag](type-aliases/InferErrorFromTag.md)
- [InfiniteQueryExecuteOptions](type-aliases/InfiniteQueryExecuteOptions.md)
- [InfiniteQueryObserverResult](type-aliases/InfiniteQueryObserverResult.md)
- [InitialDataFunction](type-aliases/InitialDataFunction.md)
- [ManagedTimerId](type-aliases/ManagedTimerId.md)
- [MutateFunction](type-aliases/MutateFunction.md)
- [MutateFunctionRest](type-aliases/MutateFunctionRest.md)
- [MutationCacheNotifyEvent](type-aliases/MutationCacheNotifyEvent.md)
- [MutationFunction](type-aliases/MutationFunction.md)
- [MutationFunctionContext](type-aliases/MutationFunctionContext.md)
- [MutationKey](type-aliases/MutationKey.md)
- [MutationMeta](type-aliases/MutationMeta.md)
- [MutationObserverResult](type-aliases/MutationObserverResult.md)
- [MutationScope](type-aliases/MutationScope.md)
- [MutationStatus](type-aliases/MutationStatus.md)
- [NetworkMode](type-aliases/NetworkMode.md)
- [NonUndefinedGuard](type-aliases/NonUndefinedGuard.md)
- [NotifyEventType](type-aliases/NotifyEventType.md)
- [NotifyOnChangeProps](type-aliases/NotifyOnChangeProps.md)
- [OmitKeyof](type-aliases/OmitKeyof.md)
- [Override](type-aliases/Override.md)
- [PlaceholderDataFunction](type-aliases/PlaceholderDataFunction.md)
- [QueriesOptions](type-aliases/QueriesOptions.md)
- [QueriesPlaceholderDataFunction](type-aliases/QueriesPlaceholderDataFunction.md)
- [QueriesResults](type-aliases/QueriesResults.md)
- [QueryBooleanOption](type-aliases/QueryBooleanOption.md)
- [QueryCacheNotifyEvent](type-aliases/QueryCacheNotifyEvent.md)
- [QueryClientProviderProps](type-aliases/QueryClientProviderProps.md)
- [QueryErrorClearResetFunction](type-aliases/QueryErrorClearResetFunction.md)
- [QueryErrorIsResetFunction](type-aliases/QueryErrorIsResetFunction.md)
- [QueryErrorResetBoundaryFunction](type-aliases/QueryErrorResetBoundaryFunction.md)
- [QueryErrorResetFunction](type-aliases/QueryErrorResetFunction.md)
- [QueryFunction](type-aliases/QueryFunction.md)
- [QueryFunctionContext](type-aliases/QueryFunctionContext.md)
- [QueryKey](type-aliases/QueryKey.md)
- [QueryKeyHashFunction](type-aliases/QueryKeyHashFunction.md)
- [QueryKeyWithDataTag](type-aliases/QueryKeyWithDataTag.md)
- [QueryMeta](type-aliases/QueryMeta.md)
- [QueryObserverResult](type-aliases/QueryObserverResult.md)
- [QueryPersister](type-aliases/QueryPersister.md)
- [QueryStatus](type-aliases/QueryStatus.md)
- [SkipToken](type-aliases/SkipToken.md)
- [StaleTime](type-aliases/StaleTime.md)
- [StaleTimeFunction](type-aliases/StaleTimeFunction.md)
- [SuspenseQueriesOptions](type-aliases/SuspenseQueriesOptions.md)
- [SuspenseQueriesResults](type-aliases/SuspenseQueriesResults.md)
- [ThrowOnError](type-aliases/ThrowOnError.md)
- [TimeoutCallback](type-aliases/TimeoutCallback.md)
- [TimeoutProvider](type-aliases/TimeoutProvider.md)
- [UndefinedInitialDataInfiniteOptions](type-aliases/UndefinedInitialDataInfiniteOptions.md)
- [UndefinedInitialDataOptions](type-aliases/UndefinedInitialDataOptions.md)
- [UnsetMarker](type-aliases/UnsetMarker.md)
- [UnusedSkipTokenInfiniteOptions](type-aliases/UnusedSkipTokenInfiniteOptions.md)
- [UnusedSkipTokenOptions](type-aliases/UnusedSkipTokenOptions.md)
- [Updater](type-aliases/Updater.md)
- [UseBaseMutationResult](type-aliases/UseBaseMutationResult.md)
- [UseBaseQueryResult](type-aliases/UseBaseQueryResult.md)
- [UseInfiniteQueryResult](type-aliases/UseInfiniteQueryResult.md)
- [UseMutateAsyncFunction](type-aliases/UseMutateAsyncFunction.md)
- [UseMutateFunction](type-aliases/UseMutateFunction.md)
- [UseMutationResult](type-aliases/UseMutationResult.md)
- [UsePrefetchInfiniteQueryOptions](type-aliases/UsePrefetchInfiniteQueryOptions.md)
- [UsePrefetchQueryOptions](type-aliases/UsePrefetchQueryOptions.md)
- [UseQueryResult](type-aliases/UseQueryResult.md)
- [UseSuspenseInfiniteQueryResult](type-aliases/UseSuspenseInfiniteQueryResult.md)
- [UseSuspenseQueryResult](type-aliases/UseSuspenseQueryResult.md)
- [WithRequired](type-aliases/WithRequired.md)
## Variables
- [dataTagErrorSymbol](variables/dataTagErrorSymbol.md)
- [dataTagSymbol](variables/dataTagSymbol.md)
- [defaultScheduler](variables/defaultScheduler.md)
- [environmentManager](variables/environmentManager.md)
- [focusManager](variables/focusManager.md)
- [IsRestoringProvider](variables/IsRestoringProvider.md)
- [~~isServer~~](variables/isServer.md)
- [notifyManager](variables/notifyManager.md)
- [onlineManager](variables/onlineManager.md)
- [QueryClientContext](variables/QueryClientContext.md)
- [skipToken](variables/skipToken.md)
- [timeoutManager](variables/timeoutManager.md)
- [unsetMarker](variables/unsetMarker.md)
## Functions
- [defaultShouldDehydrateMutation](functions/defaultShouldDehydrateMutation.md)
- [defaultShouldDehydrateQuery](functions/defaultShouldDehydrateQuery.md)
- [dehydrate](functions/dehydrate.md)
- [dehydrateQuery](functions/dehydrateQuery.md)
- [experimental\_streamedQuery](functions/experimental_streamedQuery.md)
- [hashKey](functions/hashKey.md)
- [hydrate](functions/hydrate.md)
- [HydrationBoundary](functions/HydrationBoundary.md)
- [infiniteQueryOptions](functions/infiniteQueryOptions.md)
- [~~isCancelledError~~](functions/isCancelledError.md)
- [keepPreviousData](functions/keepPreviousData.md)
- [matchMutation](functions/matchMutation.md)
- [matchQuery](functions/matchQuery.md)
- [mutationOptions](functions/mutationOptions.md)
- [noop](functions/noop.md)
- [partialMatchKey](functions/partialMatchKey.md)
- [QueryClientProvider](functions/QueryClientProvider.md)
- [QueryErrorResetBoundary](functions/QueryErrorResetBoundary.md)
- [queryOptions](functions/queryOptions.md)
- [replaceEqualDeep](functions/replaceEqualDeep.md)
- [shouldThrowError](functions/shouldThrowError.md)
- [useInfiniteQuery](functions/useInfiniteQuery.md)
- [useIsFetching](functions/useIsFetching.md)
- [useIsMutating](functions/useIsMutating.md)
- [useIsRestoring](functions/useIsRestoring.md)
- [useMutation](functions/useMutation.md)
- [useMutationState](functions/useMutationState.md)
- [usePrefetchInfiniteQuery](functions/usePrefetchInfiniteQuery.md)
- [usePrefetchQuery](functions/usePrefetchQuery.md)
- [useQueries](functions/useQueries.md)
- [useQuery](functions/useQuery.md)
- [useQueryClient](functions/useQueryClient.md)
- [useQueryErrorResetBoundary](functions/useQueryErrorResetBoundary.md)
- [useSuspenseInfiniteQuery](functions/useSuspenseInfiniteQuery.md)
- [useSuspenseQueries](functions/useSuspenseQueries.md)
- [useSuspenseQuery](functions/useSuspenseQuery.md)

View File

@@ -0,0 +1,26 @@
---
id: CancelOptions
title: CancelOptions
---
Defined in: [packages/query-core/src/types.ts:1521](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L1521)
## Properties
### revert?
```ts
optional revert: boolean;
```
Defined in: [packages/query-core/src/types.ts:1522](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L1522)
***
### silent?
```ts
optional silent: boolean;
```
Defined in: [packages/query-core/src/types.ts:1523](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L1523)

View File

@@ -0,0 +1,84 @@
---
id: DefaultOptions
title: DefaultOptions
---
Defined in: [packages/query-core/src/types.ts:1507](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L1507)
## Type Parameters
### TError
`TError` = [`DefaultError`](../type-aliases/DefaultError.md)
## Properties
### dehydrate?
```ts
optional dehydrate: DehydrateOptions;
```
Defined in: [packages/query-core/src/types.ts:1518](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L1518)
Default options used when dehydrating the client's caches; see [DehydrateOptions](DehydrateOptions.md).
***
### hydrate?
```ts
optional hydrate: object;
```
Defined in: [packages/query-core/src/types.ts:1516](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L1516)
Default options used when hydrating queries; see [HydrateOptions](HydrateOptions.md).
#### deserializeData?
```ts
optional deserializeData: TransformerFn;
```
Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`.
#### mutations?
```ts
optional mutations: MutationOptions<unknown, Error, unknown, unknown>;
```
Default options merged into every mutation restored from the dehydrated state.
#### queries?
```ts
optional queries: QueryOptions<unknown, Error, unknown, readonly unknown[], never>;
```
Default options merged into every query restored from the dehydrated state.
***
### mutations?
```ts
optional mutations: MutationObserverOptions<unknown, TError, unknown, unknown>;
```
Defined in: [packages/query-core/src/types.ts:1514](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L1514)
Default options applied to every mutation, unless overridden per-mutation.
***
### queries?
```ts
optional queries: OmitKeyof<QueryObserverOptions<unknown, TError, unknown, unknown, readonly unknown[], never>, "queryKey" | "suspense", "strictly">;
```
Defined in: [packages/query-core/src/types.ts:1509](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L1509)
Default options applied to every query, unless overridden per-query.

View File

@@ -0,0 +1,89 @@
---
id: DehydrateOptions
title: DehydrateOptions
---
Defined in: [packages/query-core/src/hydration.ts:42](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L42)
Options for `dehydrate`, controlling which queries/mutations are included in the resulting `DehydratedState` and
how their data/errors are transformed before being serialized (e.g. for embedding in server-rendered markup).
## Properties
### serializeData?
```ts
optional serializeData: TransformerFn;
```
Defined in: [packages/query-core/src/hydration.ts:44](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L44)
Transforms a query's `data` before it is dehydrated. Useful for non-JSON-serializable data.
***
### shouldDehydrateMutation()?
```ts
optional shouldDehydrateMutation: (mutation) => boolean;
```
Defined in: [packages/query-core/src/hydration.ts:46](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L46)
Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`.
#### Parameters
##### mutation
[`Mutation`](../classes/Mutation.md)
#### Returns
`boolean`
***
### shouldDehydrateQuery()?
```ts
optional shouldDehydrateQuery: (query) => boolean;
```
Defined in: [packages/query-core/src/hydration.ts:48](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L48)
Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`.
#### Parameters
##### query
[`Query`](../classes/Query.md)
#### Returns
`boolean`
***
### shouldRedactErrors()?
```ts
optional shouldRedactErrors: (error) => boolean;
```
Defined in: [packages/query-core/src/hydration.ts:54](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L54)
Predicate to decide whether a query's error should be redacted before dehydration. Errors are redacted
(replaced with a generic `Error('redacted')`) unless this function is provided and returns `false` for the
given error, in which case the original error is kept.
#### Parameters
##### error
`unknown`
#### Returns
`boolean`

View File

@@ -0,0 +1,30 @@
---
id: DehydratedState
title: DehydratedState
---
Defined in: [packages/query-core/src/hydration.ts:94](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L94)
A serializable snapshot of a `QueryClient`'s cache, as produced by `dehydrate` and consumed by `hydrate`. Typically
transported from server to client (e.g. embedded in server-rendered markup) to seed the client's cache with data
that has already been fetched, avoiding a redundant fetch on the client.
## Properties
### mutations
```ts
mutations: DehydratedMutation[];
```
Defined in: [packages/query-core/src/hydration.ts:95](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L95)
***
### queries
```ts
queries: DehydratedQuery[];
```
Defined in: [packages/query-core/src/hydration.ts:96](https://github.com/TanStack/query/blob/main/packages/query-core/src/hydration.ts#L96)

View File

@@ -0,0 +1,350 @@
---
id: EnsureQueryDataOptions
title: EnsureQueryDataOptions
---
Defined in: [packages/query-core/src/types.ts:614](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L614)
## Deprecated
## Extends
- [`FetchQueryOptions`](FetchQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>
## Type Parameters
### TQueryFnData
`TQueryFnData` = `unknown`
### TError
`TError` = [`DefaultError`](../type-aliases/DefaultError.md)
### TData
`TData` = `TQueryFnData`
### TQueryKey
`TQueryKey` *extends* [`QueryKey`](../type-aliases/QueryKey.md) = [`QueryKey`](../type-aliases/QueryKey.md)
### TPageParam
`TPageParam` = `never`
## Properties
### ~~gcTime?~~
```ts
optional gcTime: number;
```
Defined in: [packages/query-core/src/types.ts:277](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L277)
The time in milliseconds that unused/inactive cache data remains in memory.
When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration.
When different garbage collection times are specified, the longest one will be used.
Setting it to `Infinity` will disable garbage collection.
Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR.
Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see
`timeoutManager.setTimeoutProvider` for a workaround.
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`gcTime`](FetchQueryOptions.md#gctime)
***
### ~~initialData?~~
```ts
optional initialData:
| TData
| InitialDataFunction<TData>;
```
Defined in: [packages/query-core/src/types.ts:317](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L317)
If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
created or cached yet).
If set to a function, the function will be called **once** during the shared/root query initialization, and be
expected to synchronously return the initial data.
Initial data is considered stale by default unless a `staleTime` has been set.
`initialData` **is persisted** to the cache.
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`initialData`](FetchQueryOptions.md#initialdata)
***
### ~~initialDataUpdatedAt?~~
```ts
optional initialDataUpdatedAt: number | () => number | undefined;
```
Defined in: [packages/query-core/src/types.ts:321](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L321)
If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated.
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`initialDataUpdatedAt`](FetchQueryOptions.md#initialdataupdatedat)
***
### ~~initialPageParam?~~
```ts
optional initialPageParam: undefined;
```
Defined in: [packages/query-core/src/types.ts:605](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L605)
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`initialPageParam`](FetchQueryOptions.md#initialpageparam)
***
### ~~maxPages?~~
```ts
optional maxPages: number;
```
Defined in: [packages/query-core/src/types.ts:345](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L345)
Maximum number of pages to store in the data of an infinite query.
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`maxPages`](FetchQueryOptions.md#maxpages)
***
### ~~meta?~~
```ts
optional meta: Record<string, unknown>;
```
Defined in: [packages/query-core/src/types.ts:341](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L341)
Additional payload to be stored on each query.
Use this property to pass information that can be used in other places.
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`meta`](FetchQueryOptions.md#meta)
***
### ~~networkMode?~~
```ts
optional networkMode: NetworkMode;
```
Defined in: [packages/query-core/src/types.ts:265](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L265)
Controls whether a query is allowed to run based on the current network connectivity.
Defaults to `'online'`.
#### See
[Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information.
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`networkMode`](FetchQueryOptions.md#networkmode)
***
### ~~persister?~~
```ts
optional persister: QueryPersister<TQueryFnData, NoInfer<TQueryKey>, TPageParam>;
```
Defined in: [packages/query-core/src/types.ts:290](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L290)
This option can be used to persist the result of a query to an external storage, bypassing the need to actually
call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries.
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`persister`](FetchQueryOptions.md#persister)
***
### ~~queryFn?~~
```ts
optional queryFn:
| typeof skipToken
| QueryFunction<TQueryFnData, TQueryKey, TPageParam>;
```
Defined in: [packages/query-core/src/types.ts:285](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L285)
The function that the query will use to request data.
Required, unless a default query function has been set via `queryClient.setQueryDefaults` or
`queryClient.setDefaultOptions`.
Receives a [QueryFunctionContext](../type-aliases/QueryFunctionContext.md).
Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`.
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`queryFn`](FetchQueryOptions.md#queryfn)
***
### ~~queryHash?~~
```ts
optional queryHash: string;
```
Defined in: [packages/query-core/src/types.ts:295](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L295)
The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used
as the actual cache key internally.
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`queryHash`](FetchQueryOptions.md#queryhash)
***
### ~~queryKey~~
```ts
queryKey: TQueryKey & object;
```
Defined in: [packages/query-core/src/types.ts:304](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L304)
The query key to use for this query.
The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys)
for more information.
The query will automatically update when this key changes (as long as `enabled` is not set to `false`).
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`queryKey`](FetchQueryOptions.md#querykey)
***
### ~~queryKeyHashFn?~~
```ts
optional queryKeyHashFn: QueryKeyHashFunction<TQueryKey>;
```
Defined in: [packages/query-core/src/types.ts:308](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L308)
If specified, this function is used to hash the `queryKey` to a string.
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`queryKeyHashFn`](FetchQueryOptions.md#querykeyhashfn)
***
### ~~retry?~~
```ts
optional retry: RetryValue<TError>;
```
Defined in: [packages/query-core/src/types.ts:246](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L246)
If `false`, failed queries will not retry by default.
If `true`, failed queries will retry infinitely.
If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number.
If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false.
Defaults to `3` on the client and `0` on the server.
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`retry`](FetchQueryOptions.md#retry)
***
### ~~retryDelay?~~
```ts
optional retryDelay: RetryDelayValue<TError>;
```
Defined in: [packages/query-core/src/types.ts:258](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L258)
This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the
next attempt in milliseconds.
A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential
backoff.
A function like `attempt => attempt * 1000` applies linear backoff.
Defaults to a function that applies exponential backoff, capped at 30 seconds.
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`retryDelay`](FetchQueryOptions.md#retrydelay)
***
### ~~revalidateIfStale?~~
```ts
optional revalidateIfStale: boolean;
```
Defined in: [packages/query-core/src/types.ts:627](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L627)
***
### ~~staleTime?~~
```ts
optional staleTime: StaleTimeFunction<TQueryFnData, TError, TData, TQueryKey>;
```
Defined in: [packages/query-core/src/types.ts:610](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L610)
The time in milliseconds after data is considered stale.
If the data is fresh it will be returned from the cache.
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`staleTime`](FetchQueryOptions.md#staletime)
***
### ~~structuralSharing?~~
```ts
optional structuralSharing: boolean | (oldData, newData) => unknown;
```
Defined in: [packages/query-core/src/types.ts:330](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L330)
Set this to `false` to disable structural sharing between query results.
Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic.
Defaults to `true`.
#### Inherited from
[`FetchQueryOptions`](FetchQueryOptions.md).[`structuralSharing`](FetchQueryOptions.md#structuralsharing)

View File

@@ -0,0 +1,46 @@
---
id: FetchNextPageOptions
title: FetchNextPageOptions
---
Defined in: [packages/query-core/src/types.ts:737](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L737)
## Extends
- [`ResultOptions`](ResultOptions.md)
## Properties
### cancelRefetch?
```ts
optional cancelRefetch: boolean;
```
Defined in: [packages/query-core/src/types.ts:746](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L746)
If set to `true`, calling `fetchNextPage` repeatedly will invoke `queryFn` every time,
whether the previous invocation has resolved or not. Also, the result from previous invocations will be ignored.
If set to `false`, calling `fetchNextPage` repeatedly won't have any effect until the first invocation has resolved.
Defaults to `true`.
***
### throwOnError?
```ts
optional throwOnError: boolean;
```
Defined in: [packages/query-core/src/types.ts:701](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L701)
If set to `true`, the method throws if any of the underlying query refetch tasks fail.
Defaults to `false`, in which case failed refetches are swallowed and not surfaced to the
caller.
#### Inherited from
[`ResultOptions`](ResultOptions.md).[`throwOnError`](ResultOptions.md#throwonerror)

View File

@@ -0,0 +1,46 @@
---
id: FetchPreviousPageOptions
title: FetchPreviousPageOptions
---
Defined in: [packages/query-core/src/types.ts:749](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L749)
## Extends
- [`ResultOptions`](ResultOptions.md)
## Properties
### cancelRefetch?
```ts
optional cancelRefetch: boolean;
```
Defined in: [packages/query-core/src/types.ts:758](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L758)
If set to `true`, calling `fetchPreviousPage` repeatedly will invoke `queryFn` every time,
whether the previous invocation has resolved or not. Also, the result from previous invocations will be ignored.
If set to `false`, calling `fetchPreviousPage` repeatedly won't have any effect until the first invocation has resolved.
Defaults to `true`.
***
### throwOnError?
```ts
optional throwOnError: boolean;
```
Defined in: [packages/query-core/src/types.ts:701](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L701)
If set to `true`, the method throws if any of the underlying query refetch tasks fail.
Defaults to `false`, in which case failed refetches are swallowed and not surfaced to the
caller.
#### Inherited from
[`ResultOptions`](ResultOptions.md).[`throwOnError`](ResultOptions.md#throwonerror)

View File

@@ -0,0 +1,364 @@
---
id: FetchQueryOptions
title: FetchQueryOptions
---
Defined in: [packages/query-core/src/types.ts:595](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L595)
## Deprecated
## Extends
- [`WithRequired`](../type-aliases/WithRequired.md)\<[`QueryOptions`](QueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`, `TPageParam`\>, `"queryKey"`\>
## Extended by
- [`EnsureQueryDataOptions`](EnsureQueryDataOptions.md)
## Type Parameters
### TQueryFnData
`TQueryFnData` = `unknown`
### TError
`TError` = [`DefaultError`](../type-aliases/DefaultError.md)
### TData
`TData` = `TQueryFnData`
### TQueryKey
`TQueryKey` *extends* [`QueryKey`](../type-aliases/QueryKey.md) = [`QueryKey`](../type-aliases/QueryKey.md)
### TPageParam
`TPageParam` = `never`
## Properties
### ~~gcTime?~~
```ts
optional gcTime: number;
```
Defined in: [packages/query-core/src/types.ts:277](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L277)
The time in milliseconds that unused/inactive cache data remains in memory.
When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration.
When different garbage collection times are specified, the longest one will be used.
Setting it to `Infinity` will disable garbage collection.
Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR.
Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see
`timeoutManager.setTimeoutProvider` for a workaround.
#### Inherited from
```ts
WithRequired.gcTime
```
***
### ~~initialData?~~
```ts
optional initialData:
| TData
| InitialDataFunction<TData>;
```
Defined in: [packages/query-core/src/types.ts:317](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L317)
If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
created or cached yet).
If set to a function, the function will be called **once** during the shared/root query initialization, and be
expected to synchronously return the initial data.
Initial data is considered stale by default unless a `staleTime` has been set.
`initialData` **is persisted** to the cache.
#### Inherited from
```ts
WithRequired.initialData
```
***
### ~~initialDataUpdatedAt?~~
```ts
optional initialDataUpdatedAt: number | () => number | undefined;
```
Defined in: [packages/query-core/src/types.ts:321](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L321)
If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated.
#### Inherited from
```ts
WithRequired.initialDataUpdatedAt
```
***
### ~~initialPageParam?~~
```ts
optional initialPageParam: undefined;
```
Defined in: [packages/query-core/src/types.ts:605](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L605)
***
### ~~maxPages?~~
```ts
optional maxPages: number;
```
Defined in: [packages/query-core/src/types.ts:345](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L345)
Maximum number of pages to store in the data of an infinite query.
#### Inherited from
```ts
WithRequired.maxPages
```
***
### ~~meta?~~
```ts
optional meta: Record<string, unknown>;
```
Defined in: [packages/query-core/src/types.ts:341](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L341)
Additional payload to be stored on each query.
Use this property to pass information that can be used in other places.
#### Inherited from
```ts
WithRequired.meta
```
***
### ~~networkMode?~~
```ts
optional networkMode: NetworkMode;
```
Defined in: [packages/query-core/src/types.ts:265](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L265)
Controls whether a query is allowed to run based on the current network connectivity.
Defaults to `'online'`.
#### See
[Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information.
#### Inherited from
```ts
WithRequired.networkMode
```
***
### ~~persister?~~
```ts
optional persister: QueryPersister<TQueryFnData, NoInfer<TQueryKey>, TPageParam>;
```
Defined in: [packages/query-core/src/types.ts:290](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L290)
This option can be used to persist the result of a query to an external storage, bypassing the need to actually
call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries.
#### Inherited from
```ts
WithRequired.persister
```
***
### ~~queryFn?~~
```ts
optional queryFn:
| typeof skipToken
| QueryFunction<TQueryFnData, TQueryKey, TPageParam>;
```
Defined in: [packages/query-core/src/types.ts:285](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L285)
The function that the query will use to request data.
Required, unless a default query function has been set via `queryClient.setQueryDefaults` or
`queryClient.setDefaultOptions`.
Receives a [QueryFunctionContext](../type-aliases/QueryFunctionContext.md).
Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`.
#### Inherited from
```ts
WithRequired.queryFn
```
***
### ~~queryHash?~~
```ts
optional queryHash: string;
```
Defined in: [packages/query-core/src/types.ts:295](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L295)
The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used
as the actual cache key internally.
#### Inherited from
```ts
WithRequired.queryHash
```
***
### ~~queryKey~~
```ts
queryKey: TQueryKey & object;
```
Defined in: [packages/query-core/src/types.ts:304](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L304)
The query key to use for this query.
The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys)
for more information.
The query will automatically update when this key changes (as long as `enabled` is not set to `false`).
#### Inherited from
```ts
WithRequired.queryKey
```
***
### ~~queryKeyHashFn?~~
```ts
optional queryKeyHashFn: QueryKeyHashFunction<TQueryKey>;
```
Defined in: [packages/query-core/src/types.ts:308](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L308)
If specified, this function is used to hash the `queryKey` to a string.
#### Inherited from
```ts
WithRequired.queryKeyHashFn
```
***
### ~~retry?~~
```ts
optional retry: RetryValue<TError>;
```
Defined in: [packages/query-core/src/types.ts:246](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L246)
If `false`, failed queries will not retry by default.
If `true`, failed queries will retry infinitely.
If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number.
If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false.
Defaults to `3` on the client and `0` on the server.
#### Inherited from
```ts
WithRequired.retry
```
***
### ~~retryDelay?~~
```ts
optional retryDelay: RetryDelayValue<TError>;
```
Defined in: [packages/query-core/src/types.ts:258](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L258)
This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the
next attempt in milliseconds.
A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential
backoff.
A function like `attempt => attempt * 1000` applies linear backoff.
Defaults to a function that applies exponential backoff, capped at 30 seconds.
#### Inherited from
```ts
WithRequired.retryDelay
```
***
### ~~staleTime?~~
```ts
optional staleTime: StaleTimeFunction<TQueryFnData, TError, TData, TQueryKey>;
```
Defined in: [packages/query-core/src/types.ts:610](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L610)
The time in milliseconds after data is considered stale.
If the data is fresh it will be returned from the cache.
***
### ~~structuralSharing?~~
```ts
optional structuralSharing: boolean | (oldData, newData) => unknown;
```
Defined in: [packages/query-core/src/types.ts:330](https://github.com/TanStack/query/blob/main/packages/query-core/src/types.ts#L330)
Set this to `false` to disable structural sharing between query results.
Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic.
Defaults to `true`.
#### Inherited from
```ts
WithRequired.structuralSharing
```

View File

@@ -0,0 +1,237 @@
---
id: FocusManager
title: FocusManager
---
Defined in: [packages/query-core/src/focusManager.ts:14](https://github.com/TanStack/query/blob/main/packages/query-core/src/focusManager.ts#L14)
The `FocusManager` manages the focus state within TanStack Query.
It can be used to change the default event listeners or to manually change the focus state.
## Extends
- `Subscribable`\<`Listener`\>
## Properties
### listeners
```ts
protected listeners: Set<Listener>;
```
Defined in: [packages/query-core/src/subscribable.ts:2](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L2)
#### Inherited from
```ts
Subscribable.listeners
```
## Methods
### hasListeners()
```ts
hasListeners(): boolean;
```
Defined in: [packages/query-core/src/subscribable.ts:19](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L19)
#### Returns
`boolean`
#### Inherited from
```ts
Subscribable.hasListeners
```
***
### isFocused()
```ts
isFocused(): boolean;
```
Defined in: [packages/query-core/src/focusManager.ts:128](https://github.com/TanStack/query/blob/main/packages/query-core/src/focusManager.ts#L128)
`isFocused` can be used to get the current focus state.
#### Returns
`boolean`
***
### onFocus()
```ts
onFocus(): void;
```
Defined in: [packages/query-core/src/focusManager.ts:118](https://github.com/TanStack/query/blob/main/packages/query-core/src/focusManager.ts#L118)
`onFocus` notifies all subscribed listeners with the current focus state.
#### Returns
`void`
***
### onSubscribe()
```ts
protected onSubscribe(): void;
```
Defined in: [packages/query-core/src/focusManager.ts:39](https://github.com/TanStack/query/blob/main/packages/query-core/src/focusManager.ts#L39)
#### Returns
`void`
#### Overrides
```ts
Subscribable.onSubscribe
```
***
### onUnsubscribe()
```ts
protected onUnsubscribe(): void;
```
Defined in: [packages/query-core/src/focusManager.ts:45](https://github.com/TanStack/query/blob/main/packages/query-core/src/focusManager.ts#L45)
#### Returns
`void`
#### Overrides
```ts
Subscribable.onUnsubscribe
```
***
### setEventListener()
```ts
setEventListener(setup): void;
```
Defined in: [packages/query-core/src/focusManager.ts:77](https://github.com/TanStack/query/blob/main/packages/query-core/src/focusManager.ts#L77)
`setEventListener` can be used to set a custom event listener that will
be used to determine the focus state. The provided `setup` function
receives a `setFocused` callback: call it with a `boolean` to manually
set the focus state, or with no arguments to re-evaluate the current
focus state and notify subscribers.
#### Parameters
##### setup
`SetupFn`
#### Returns
`void`
#### Example
```ts
import { focusManager } from '@tanstack/query-core'
focusManager.setEventListener((handleFocus) => {
const listener = () => handleFocus()
// Listen to visibilitychange
if (typeof window !== 'undefined' && window.addEventListener) {
window.addEventListener('visibilitychange', listener, false)
}
return () => {
// Be sure to unsubscribe if a new handler is set
window.removeEventListener('visibilitychange', listener)
}
})
```
***
### setFocused()
```ts
setFocused(focused?): void;
```
Defined in: [packages/query-core/src/focusManager.ts:107](https://github.com/TanStack/query/blob/main/packages/query-core/src/focusManager.ts#L107)
`setFocused` can be used to manually set the focus state. Set `undefined`
to fall back to the default focus check.
#### Parameters
##### focused?
`boolean`
#### Returns
`void`
#### Example
```ts
import { focusManager } from '@tanstack/query-core'
// Set focused
focusManager.setFocused(true)
// Set unfocused
focusManager.setFocused(false)
// Fallback to the default focus check
focusManager.setFocused(undefined)
```
***
### subscribe()
```ts
subscribe(listener): () => void;
```
Defined in: [packages/query-core/src/subscribable.ts:8](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L8)
#### Parameters
##### listener
`Listener`
#### Returns
```ts
(): void;
```
##### Returns
`void`
#### Inherited from
```ts
Subscribable.subscribe
```

Some files were not shown because too many files have changed in this diff Show More