### Run the Next.js App Router example Source: https://github.com/tanstack/query/blob/main/examples/react/optimistic-updates-nextjs-app-router/README.md Install dependencies and start the development server. Open http://localhost:3000 to view the example. ```sh npm install npm run dev ``` -------------------------------- ### Run an example with pnpm run dev Source: https://github.com/tanstack/query/blob/main/CONTRIBUTING.md Run in the selected example's directory to start it. Without local changes it runs against the latest TanStack Query release. ```bash pnpm run dev ``` -------------------------------- ### Install and run tanstack.com dev server Source: https://github.com/tanstack/query/blob/main/CONTRIBUTING.md Enter tanstack/tanstack.com, install dependencies, and start the app in dev mode. The app runs on https://localhost:3000 by default. ```sh cd tanstack.com pnpm i # The app will run on https://localhost:3000 by default pnpm dev ``` -------------------------------- ### Run development server with pnpm run watch Source: https://github.com/tanstack/query/blob/main/CONTRIBUTING.md Starts the development server. Also used to run examples against your local changes instead of the latest TanStack Query release. ```bash pnpm run watch ``` -------------------------------- ### Run the Next.js development server Source: https://github.com/tanstack/query/blob/main/integrations/react/next-15/README.md Start the local dev server using npm, yarn, or pnpm, then open http://localhost:3000 to view the result. Edit app/page.tsx to see auto-updates. ```bash npm run dev # or yarn dev # or pnpm dev ``` -------------------------------- ### Install @tanstack/query-persist-client-core with bun Source: https://github.com/tanstack/query/blob/main/docs/framework/react/plugins/createPersister.md Installs the @tanstack/query-persist-client-core package using bun. ```sh bun add @tanstack/query-persist-client-core ``` -------------------------------- ### Install dependencies with pnpm install Source: https://github.com/tanstack/query/blob/main/CONTRIBUTING.md Run from the repository root to install all dependencies. TanStack/query uses pnpm v11 for package management. ```bash pnpm install ``` -------------------------------- ### Run Lit examples with pnpm Source: https://github.com/tanstack/query/blob/main/packages/lit-query/README.md Runs the basic, pagination, and SSR Lit examples from the repository root. ```bash pnpm --dir examples/lit/basic run dev pnpm --dir examples/lit/pagination run dev pnpm --dir examples/lit/ssr run dev ``` -------------------------------- ### Install React Query Devtools with bun Source: https://github.com/tanstack/query/blob/main/docs/framework/react/devtools.md Install the separate @tanstack/react-query-devtools package using bun. For Next 13+ App Dir, install it as a dev dependency. ```sh bun add @tanstack/react-query-devtools ``` -------------------------------- ### Install @tanstack/query-persist-client-core with yarn Source: https://github.com/tanstack/query/blob/main/docs/framework/react/plugins/createPersister.md Installs the @tanstack/query-persist-client-core package using yarn. ```sh yarn add @tanstack/query-persist-client-core ``` -------------------------------- ### Install @tanstack/query-persist-client-core with npm Source: https://github.com/tanstack/query/blob/main/docs/framework/react/plugins/createPersister.md Installs the @tanstack/query-persist-client-core package using npm. ```sh npm install @tanstack/query-persist-client-core ``` -------------------------------- ### Pass signals directly to useQuery arguments in Solid Query Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/quick-start.md Signals and store values can be passed directly into function arguments, and Solid Query updates the query store automatically when the signal value changes. The example uses enabled() and todo() inside the useQuery options function. ```tsx import { QueryClient, QueryClientProvider, useQuery, } from '@tanstack/solid-query' import { createSignal, For } from 'solid-js' const queryClient = new QueryClient() function Example() { const [enabled, setEnabled] = createSignal(false) const [todo, setTodo] = createSignal(0) // ✅ passing a signal directly is safe and observers update // automatically when the value of a signal changes const todosQuery = useQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos, enabled: enabled(), })) const todoDetailsQuery = useQuery(() => ({ queryKey: ['todo', todo()], queryFn: fetchTodo, enabled: todo() > 0, })) return (

Loading...

Error: {todosQuery.error.message}

{(todo) => ( )}
) } function App() { return ( ) } ``` -------------------------------- ### Install @tanstack/query-persist-client-core with pnpm Source: https://github.com/tanstack/query/blob/main/docs/framework/react/plugins/createPersister.md Installs the @tanstack/query-persist-client-core package using pnpm. ```sh pnpm add @tanstack/query-persist-client-core ``` -------------------------------- ### Install @tanstack/query-async-storage-persister and @tanstack/react-query-persist-client Source: https://github.com/tanstack/query/blob/main/docs/framework/react/plugins/createAsyncStoragePersister.md Install the required packages using npm, pnpm, yarn, or bun. ```sh npm install @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` ```sh pnpm add @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` ```sh yarn add @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` ```sh bun add @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` -------------------------------- ### Install with bun Source: https://github.com/tanstack/query/blob/main/docs/framework/angular/installation.md Install the experimental Angular Query package using bun. The library is experimental and compatible with Angular v16+. ```sh bun add @tanstack/angular-query-experimental ``` -------------------------------- ### Install React Query Devtools with npm Source: https://github.com/tanstack/query/blob/main/docs/framework/react/devtools.md Install the separate @tanstack/react-query-devtools package using npm. For Next 13+ App Dir, install it as a dev dependency. ```sh npm i @tanstack/react-query-devtools ``` -------------------------------- ### Install @testing-library/preact Source: https://github.com/tanstack/query/blob/main/docs/framework/preact/guides/testing.md Install @testing-library/preact as a development dependency to access renderHook and DOM testing utilities. ```sh npm install @testing-library/preact --save-dev ``` -------------------------------- ### setOptions() example Source: https://github.com/tanstack/query/blob/main/docs/framework/angular/reference/classes/MutationObserver.md Example of setting options with mutationFn and onSuccess. ```ts observer.setOptions({ mutationFn: (variables: { title: string }) => addPost(variables), onSuccess: (data) => console.log(data), }) ``` -------------------------------- ### Install @tanstack/svelte-query with bun Source: https://github.com/tanstack/query/blob/main/docs/framework/svelte/installation.md Installs Svelte Query via bun as an alternative to npm. ```sh bun add @tanstack/svelte-query ``` -------------------------------- ### Install React Query Devtools with pnpm Source: https://github.com/tanstack/query/blob/main/docs/framework/react/devtools.md Install the separate @tanstack/react-query-devtools package using pnpm. For Next 13+ App Dir, install it as a dev dependency. ```sh pnpm add @tanstack/react-query-devtools ``` -------------------------------- ### Install @tanstack/solid-query with bun Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/installation.md Installs Solid Query using bun as an alternative package manager. ```sh bun add @tanstack/solid-query ``` -------------------------------- ### Install React Query Devtools with yarn Source: https://github.com/tanstack/query/blob/main/docs/framework/react/devtools.md Install the separate @tanstack/react-query-devtools package using yarn. For Next 13+ App Dir, install it as a dev dependency. ```sh yarn add @tanstack/react-query-devtools ``` -------------------------------- ### Install Solid Query Devtools with bun Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/devtools.md Installs the separate @tanstack/solid-query-devtools package using bun. ```sh bun add @tanstack/solid-query-devtools ``` -------------------------------- ### Run Lit examples on custom ports Source: https://github.com/tanstack/query/blob/main/packages/lit-query/README.md Runs the Lit examples on custom ports and host using environment variables. ```bash DEMO_PORT=4180 pnpm --dir examples/lit/basic run dev PAGINATION_DEMO_PORT=4181 PAGINATION_API_PORT=4182 pnpm --dir examples/lit/pagination run dev SSR_PORT=4180 pnpm --dir examples/lit/ssr run dev SSR_HOST=0.0.0.0 pnpm --dir examples/lit/ssr run dev ``` -------------------------------- ### Vitest setup file for jest-dom and QueryClientProvider Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/guides/testing.md Setup file that loads jest-dom matchers and registers the QueryClientProvider custom element for tests. ```ts import '@testing-library/jest-dom/vitest' import { QueryClientProvider } from '@tanstack/lit-query' customElements.define('query-client-provider', QueryClientProvider) ``` -------------------------------- ### fetchNextPage() example Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/reference/classes/InfiniteQueryObserver.md Example of using fetchNextPage to fetch the next page when hasNextPage is true. ```ts const { hasNextPage } = observer.getCurrentResult() if (hasNextPage) { await observer.fetchNextPage() } ``` -------------------------------- ### Install @tanstack/react-query with bun Source: https://github.com/tanstack/query/blob/main/docs/framework/react/installation.md Install React Query using bun as an alternative package manager. ```sh bun add @tanstack/react-query ``` -------------------------------- ### setOnline() example Source: https://github.com/tanstack/query/blob/main/docs/framework/angular/reference/interfaces/OnlineManager.md Example of manually setting the online state to online and offline using `setOnline`. ```ts import { onlineManager } from '@tanstack/query-core' // Set to online onlineManager.setOnline(true) // Set to offline onlineManager.setOnline(false) ``` -------------------------------- ### Setup jest-dom matchers Source: https://github.com/tanstack/query/blob/main/docs/framework/svelte/testing.md Setup file for jest-dom matchers. ```ts import '@testing-library/jest-dom/vitest' ``` -------------------------------- ### Install @tanstack/react-query with deno Source: https://github.com/tanstack/query/blob/main/docs/framework/react/installation.md Install React Query using deno as an alternative package manager. ```sh deno add @tanstack/react-query ``` -------------------------------- ### fetchPreviousPage() example Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/reference/classes/InfiniteQueryObserver.md Example of using fetchPreviousPage to fetch the previous page when hasPreviousPage is true. ```ts const { hasPreviousPage } = observer.getCurrentResult() if (hasPreviousPage) { await observer.fetchPreviousPage() } ``` -------------------------------- ### Install with npm Source: https://github.com/tanstack/query/blob/main/docs/framework/angular/installation.md Install the experimental Angular Query package using npm. The library is experimental and compatible with Angular v16+. ```sh npm i @tanstack/angular-query-experimental ``` -------------------------------- ### Install with yarn Source: https://github.com/tanstack/query/blob/main/docs/framework/angular/installation.md Install the experimental Angular Query package using yarn. The library is experimental and compatible with Angular v16+. ```sh yarn add @tanstack/angular-query-experimental ``` -------------------------------- ### Set up QueryClientProvider and useQuery in SolidJS Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/quick-start.md Create a QueryClient and wrap the app in QueryClientProvider, then fetch todos with useQuery and render pending, error, and success states using Solid's Switch/Match/For. ```tsx import { QueryClient, QueryClientProvider, useQuery, } from '@tanstack/solid-query' import { Switch, Match, For } from 'solid-js' const queryClient = new QueryClient() function Example() { const query = useQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos, })) return (

Loading...

Error: {query.error.message}

{(todo) =>

{todo.title}

}
) } function App() { return ( ) } ``` -------------------------------- ### Use useQuery with ``` -------------------------------- ### Install with pnpm Source: https://github.com/tanstack/query/blob/main/docs/framework/angular/installation.md Install the experimental Angular Query package using pnpm. The library is experimental and compatible with Angular v16+. ```sh pnpm add @tanstack/angular-query-experimental ``` -------------------------------- ### Install testing dependencies Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/guides/testing.md Install Vitest, jsdom, and jest-dom matchers as dev dependencies to set up the testing environment. ```sh npm install vitest jsdom @testing-library/jest-dom --save-dev ``` -------------------------------- ### Install @tanstack/query-sync-storage-persister and @tanstack/react-query-persist-client Source: https://github.com/tanstack/query/blob/main/docs/framework/react/plugins/createSyncStoragePersister.md Install the required packages using your preferred package manager. The utility is available under the '@tanstack/query-sync-storage-persister' import. ```sh npm install @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` ```sh pnpm add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` ```sh yarn add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` ```sh bun add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` -------------------------------- ### QueryCache.get() example Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/reference/classes/QueryCache.md Example of using get to retrieve a query by its hash. ```ts const queryCache = queryClient.getQueryCache() const queryHash = hashKey(['posts']) const query = queryCache.get(queryHash) ``` -------------------------------- ### Install @tanstack/lit-query with npm, pnpm, yarn, or bun Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/installation.md Install the experimental Lit adapter using your package manager. Pin exact versions if you need extra release stability while the API is early. ```sh npm i @tanstack/lit-query ``` ```sh pnpm add @tanstack/lit-query ``` ```sh yarn add @tanstack/lit-query ``` ```sh bun add @tanstack/lit-query ``` -------------------------------- ### Install Solid Query Devtools with pnpm Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/devtools.md Installs the separate @tanstack/solid-query-devtools package using pnpm. ```sh pnpm add @tanstack/solid-query-devtools ``` -------------------------------- ### Install Preact Query Devtools with bun Source: https://github.com/tanstack/query/blob/main/docs/framework/preact/devtools.md Install the Preact Query Devtools package using bun. ```sh bun add @tanstack/preact-query-devtools ``` -------------------------------- ### subscribe usage example Source: https://github.com/tanstack/query/blob/main/docs/framework/angular/reference/classes/InfiniteQueryObserver.md Example of subscribing to updates and then unsubscribing using the returned function. ```ts const unsubscribe = subscribable.subscribe(() => { // react to the update }) unsubscribe() ``` -------------------------------- ### Install Solid Query Devtools with npm Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/devtools.md Installs the separate @tanstack/solid-query-devtools package using npm. ```sh npm i @tanstack/solid-query-devtools ``` -------------------------------- ### Use useQueryClient in a Vue component Source: https://github.com/tanstack/query/blob/main/docs/framework/vue/reference/functions/useQueryClient.md Use useQueryClient inside a Vue component's setup to access the installed QueryClient and invalidate queries. The id parameter is only needed when multiple QueryClients are installed in the same app. ```vue ``` -------------------------------- ### Quick Start with createQueryController and QueryClientProvider Source: https://github.com/tanstack/query/blob/main/packages/lit-query/README.md Sets up a QueryClient, provides it via QueryClientProvider, and uses createQueryController to fetch and render users in a LitElement. ```ts import { QueryClient, QueryClientProvider, createQueryController, } from '@tanstack/lit-query' import { LitElement, html } from 'lit' const client = new QueryClient({ defaultOptions: { queries: { retry: false } }, }) class AppProvider extends QueryClientProvider { constructor() { super() this.client = client } } customElements.define('app-provider', AppProvider) class UsersView extends LitElement { private readonly users = createQueryController(this, { queryKey: ['users'], queryFn: async () => { const response = await fetch('/api/users') return response.json() as Promise> }, }) render() { const query = this.users() if (query.isPending) return html`Loading...` if (query.isError) return html`Error` return html`` } } customElements.define('users-view', UsersView) ``` -------------------------------- ### Basic useQuery with Solid Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/reference/functions/useQuery.md Use this basic useQuery example to fetch and render a list of posts with loading, error, and success states. ```tsx import { For, Match, Switch } from 'solid-js' import { useQuery } from '@tanstack/solid-query' function Posts() { const postsQuery = useQuery(() => ({ queryKey: ['posts'], queryFn: fetchPosts, })) return ( Loading... Error: {postsQuery.error.message}
    {(post) =>
  • {post.title}
  • }
{postsQuery.isFetching ? 'Background Updating...' : ' '}
) } ``` -------------------------------- ### getQueryCache() example Source: https://github.com/tanstack/query/blob/main/docs/framework/angular/reference/classes/QueryClient.md Creates a QueryClient, gets its QueryCache, and finds all queries with key ['posts']. ```ts import { QueryClient } from '@tanstack/query-core' const queryClient = new QueryClient() const queryCache = queryClient.getQueryCache() const queries = queryCache.findAll({ queryKey: ['posts'] }) ``` -------------------------------- ### Use mutateAsync to get a promise from a mutation Source: https://github.com/tanstack/query/blob/main/docs/framework/react/guides/mutations.md Use mutateAsync instead of mutate to get a promise that resolves on success or throws on error. This allows composing side effects with try/catch/finally. ```tsx const mutation = useMutation({ mutationFn: addTodo }) try { const todo = await mutation.mutateAsync(todo) console.log(todo) } catch (error) { console.error(error) } finally { console.log('done') } ``` -------------------------------- ### fetchOptimistic() example Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/reference/classes/InfiniteQueryObserver.md Example of using fetchOptimistic to prefetch a query and log the result data. ```ts const result = await observer.fetchOptimistic({ queryKey: ['posts', 2], queryFn: () => fetchPost(2), }) console.log(result.data) ``` -------------------------------- ### Install Solid Query Devtools with yarn Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/devtools.md Installs the separate @tanstack/solid-query-devtools package using yarn. ```sh yarn add @tanstack/solid-query-devtools ``` -------------------------------- ### setOptions() example Source: https://github.com/tanstack/query/blob/main/docs/framework/angular/reference/classes/QueryObserver.md Example of updating observer options and later switching to a different query while reusing the same observer. ```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) }) ``` -------------------------------- ### Create tanstack directory for docs development Source: https://github.com/tanstack/query/blob/main/CONTRIBUTING.md First step for local docs setup: create a directory named tanstack that will hold both repository clones. ```sh mkdir tanstack ``` -------------------------------- ### useQueryClient function signature Source: https://github.com/tanstack/query/blob/main/docs/framework/vue/reference/functions/useQueryClient.md Retrieves the QueryClient installed by VueQueryPlugin via Vue's inject. Must be called inside setup() or another function that supports an injection context. Throws if called outside an injection context or if no QueryClient was installed via VueQueryPlugin. ```ts function useQueryClient(id?: string): QueryClient; ``` -------------------------------- ### Invalidate queries by key prefix Source: https://github.com/tanstack/query/blob/main/docs/framework/angular/guides/query-invalidation.md Invalidates matching queries starting with the specified queryKey prefix. In this example, both the base 'todos' and the parameterized 'todos' queries are invalidated. ```ts import { injectQuery, QueryClient } from '@tanstack/angular-query-experimental' class QueryInvalidationExample { readonly queryClient = inject(QueryClient) invalidateQueries() { this.queryClient.invalidateQueries({ queryKey: ['todos'] }) } // Both queries below will be invalidated todoListQuery = injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodoList, })) todoListQuery = injectQuery(() => ({ queryKey: ['todos', { page: 1 }], queryFn: fetchTodoList, })) } ``` -------------------------------- ### Set up QueryClientProvider and fetch data with createQuery Source: https://github.com/tanstack/query/blob/main/docs/framework/svelte/overview.md Configure QueryClientProvider at the project root and consume createQuery inside child components. Arguments to createQuery must be wrapped in a function to maintain reactivity in Svelte. ```svelte ``` ```svelte
{#if query.isPending}

Loading...

{:else if query.isError}

Error: {query.error.message}

{:else if query.isSuccess} {#each query.data as todo}

{todo.title}

{/each} {/if}
``` -------------------------------- ### Set up QueryClientProvider with useQuery and useMutation in Preact Source: https://github.com/tanstack/query/blob/main/docs/framework/preact/quick-start.md Creates a QueryClient and provides it to the app via QueryClientProvider. Uses useQuery to fetch todos and useMutation to add a todo, invalidating the ['todos'] query on success. ```tsx import { useQuery, useMutation, useQueryClient, QueryClient, QueryClientProvider, } from '@tanstack/preact-query' import { render } from 'preact' import { getTodos, postTodo } from '../my-api' // Create a client const queryClient = new QueryClient() function App() { return ( // Provide the client to your App ) } function Todos() { // Access the client const queryClient = useQueryClient() // Queries const query = useQuery({ queryKey: ['todos'], queryFn: getTodos }) // Mutations const mutation = useMutation({ mutationFn: postTodo, onSuccess: () => { // Invalidate and refetch queryClient.invalidateQueries({ queryKey: ['todos'] }) }, }) return (
) } render(, document.getElementById('root')) ``` -------------------------------- ### useQueryClient Source: https://github.com/tanstack/query/blob/main/docs/framework/vue/reference/functions/useQueryClient.md Retrieves the QueryClient installed by VueQueryPlugin, via Vue's inject. Must be called inside setup() or another function that supports an injection context. ```APIDOC ## useQueryClient ### Description Retrieves the `QueryClient` installed by `VueQueryPlugin`, via Vue's `inject`. Must be called inside `setup()` or another function that supports an injection context. ### Signature ```ts function useQueryClient(id?: string): QueryClient; ``` ### Parameters - **id?** (`string`) - Optional - The `queryClientKey` passed to `VueQueryPlugin` — only needed when multiple `QueryClient`s are installed in the same app. Defaults to `''`. ### Returns `QueryClient` - The installed `QueryClient`. ### Throws If called outside an injection context, or if no `QueryClient` was installed via `VueQueryPlugin`. ### Example ```vue ``` ``` -------------------------------- ### Build all packages with pnpm build:all Source: https://github.com/tanstack/query/blob/main/CONTRIBUTING.md Builds all packages in the repository before development. ```bash pnpm build:all ``` -------------------------------- ### Install Vitest, jsdom, and Svelte Testing Library Source: https://github.com/tanstack/query/blob/main/docs/framework/svelte/testing.md Install Vitest, jsdom, and Svelte Testing Library as dev dependencies. ```sh npm install vitest jsdom @testing-library/svelte @testing-library/jest-dom --save-dev ``` -------------------------------- ### Request Waterfall Example with Article and Comments Source: https://github.com/tanstack/query/blob/main/docs/framework/react/guides/prefetching.md Shows a request waterfall where Comments query starts only after Article query resolves. Use this to understand the problem before applying prefetching. ```tsx function Article({ id }) { const { data: articleData, isPending } = useQuery({ queryKey: ['article', id], queryFn: getArticleById, }) if (isPending) { return 'Loading article...' } return ( <> ) } function Comments({ id }) { const { data, isPending } = useQuery({ queryKey: ['article-comments', id], queryFn: getArticleCommentsById, }) ... } ``` -------------------------------- ### Configure TypeScript useDefineForClassFields for Lit Query Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/installation.md Set useDefineForClassFields to false in TypeScript to avoid class fields shadowing Lit's reactive property accessors. The runnable examples use this setting. ```json { "compilerOptions": { "useDefineForClassFields": false } } ``` -------------------------------- ### Install Preact Query Devtools with yarn Source: https://github.com/tanstack/query/blob/main/docs/framework/preact/devtools.md Install the Preact Query Devtools package using yarn. ```sh yarn add @tanstack/preact-query-devtools ``` -------------------------------- ### Use mutateAsync with Promise.all for multiple mutations Source: https://github.com/tanstack/query/blob/main/docs/framework/react/reference/functions/useMutation.md Callbacks passed to mutate only fire for the last call; use mutateAsync to get a promise per call and await all with Promise.all. This example adds multiple todos and handles errors. ```tsx import { useMutation, useQueryClient } from '@tanstack/react-query' function AddTodos() { const queryClient = useQueryClient() const addMutation = useMutation({ mutationFn: addTodo, onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), }) async function handleAddAll(todos: Array) { try { await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo))) } catch (error) { console.error('Failed to add todos:', error) } } return ( ) } ``` -------------------------------- ### Conditional lazy loading causing double request waterfall Source: https://github.com/tanstack/query/blob/main/docs/framework/react/guides/prefetching.md Example from the Performance & Request Waterfalls guide showing a double request waterfall when GraphFeedItem is lazy loaded and its data is fetched only after rendering. ```tsx // This lazy loads the GraphFeedItem component, meaning // it won't start loading until something renders it const GraphFeedItem = React.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 } return })} ) } // GraphFeedItem.tsx function GraphFeedItem({ feedItem }) { const { data, isPending } = useQuery({ queryKey: ['graph', feedItem.id], queryFn: getGraphDataById, }) ... } ``` -------------------------------- ### Augment Register to set defaultError with AxiosError Source: https://github.com/tanstack/query/blob/main/docs/framework/angular/reference/interfaces/Register.md Augment the installed adapter module's Register interface to override the default error type. This example uses the React adapter; augmenting @tanstack/query-core instead covers every adapter at once. ```ts // Use the module you installed — here, the React adapter. declare module '@tanstack/react-query' { interface Register { defaultError: AxiosError } } ``` -------------------------------- ### Nuxt 3 Vue Query plugin setup (vue-query.ts) Source: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/ssr.md Create this file in your Nuxt 3 plugins directory to set up Vue Query with SSR. It configures a QueryClient, installs the plugin, and dehydrates/hydrates the query state on server and client. ```ts import { VueQueryPlugin, QueryClient, hydrate, dehydrate, } from '@tanstack/vue-query' // Nuxt 3 app aliases import { defineNuxtPlugin, useState } from '#imports' import type { DehydratedState, VueQueryPluginOptions, } from '@tanstack/vue-query' export default defineNuxtPlugin((nuxt) => { const vueQueryState = useState('vue-query') // Modify your Vue Query global settings here const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 5 * 1000 } }, }) const options: VueQueryPluginOptions = { queryClient } nuxt.vueApp.use(VueQueryPlugin, options) if (import.meta.server) { nuxt.hooks.hook('app:rendered', () => { vueQueryState.value = dehydrate(queryClient) }) } if (import.meta.client && vueQueryState.value !== null) { hydrate(queryClient, vueQueryState.value) } }) ``` -------------------------------- ### setEventListener() method signature and example Source: https://github.com/tanstack/query/blob/main/docs/framework/angular/reference/interfaces/FocusManager.md `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. ```ts setEventListener(setup: SetupFn): void; ``` ```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) } }) ``` -------------------------------- ### Set up QueryClientProvider with per-request QueryClient in SolidStart Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/guides/ssr.md Create the QueryClient inside the App component so SolidStart makes a fresh one per request, preventing cached data from being shared between users. The Suspense boundary is required because useQuery suspends while pending on both server and client. ```tsx // src/app.tsx import { MetaProvider, Title } from '@solidjs/meta' import { Router } from '@solidjs/router' import { FileRoutes } from '@solidjs/start/router' import { QueryClient, QueryClientProvider } from '@tanstack/solid-query' import { Suspense } from 'solid-js' export default function App() { // Constructing the QueryClient inside the component (rather than at module // scope) means SolidStart creates a fresh one for every request, so data // is never shared between users. const queryClient = new QueryClient({ defaultOptions: { queries: { // staleTime governs refetches from later triggers (a new mount, window // focus, and so on) — see Solid Query's hydration model above for why // the very first mount after SSR doesn't need it to skip a refetch. staleTime: 5 * 1000, }, }, }) return ( ( My App {props.children} )} > ) } ``` -------------------------------- ### createInfiniteQueryController Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/reference/functions/createInfiniteQueryController.md Creates a Lit reactive controller that subscribes the host to an infinite query. The returned accessor is callable and also exposes current, refetch, fetchNextPage, fetchPreviousPage, and destroy. When options is a function, it is re-read during host updates so query keys and options can follow reactive host state. If queryClient is omitted, the controller resolves the client from the nearest connected QueryClientProvider. ```APIDOC ## createInfiniteQueryController ### Description Creates a Lit reactive controller that subscribes the host to an infinite query. ### Signature ```ts function createInfiniteQueryController< TQueryFnData = unknown, TError = Error, TData = InfiniteData, TQueryKey extends readonly unknown[] = readonly unknown[], TPageParam = unknown >( host: ReactiveControllerHost, options: Accessor< CreateInfiniteQueryOptions >, queryClient?: QueryClient ): InfiniteQueryResultAccessor; ``` ### Type Parameters - **TQueryFnData** = `unknown` - **TError** = `Error` - **TData** = `InfiniteData` - **TQueryKey** extends `readonly unknown[]` = `readonly unknown[]` - **TPageParam** = `unknown` ### Parameters - **host** (`ReactiveControllerHost`) - The Lit reactive controller host that owns the infinite query subscription. - **options** (`Accessor>`) - Infinite query observer options, or a getter that returns options. - **queryClient?** (`QueryClient`) - Optional explicit query client. Provide this for controllers that should not resolve a client from Lit context. ### Returns `InfiniteQueryResultAccessor` - An accessor for the latest infinite query result with page helper methods. ### Example ```ts import { LitElement, html } from 'lit' import { createInfiniteQueryController } from '@tanstack/lit-query' class ProjectsView extends LitElement { private readonly projects = createInfiniteQueryController(this, { queryKey: ['projects'], queryFn: ({ pageParam }) => fetchProjects(pageParam), initialPageParam: 0, getNextPageParam: (lastPage) => lastPage.nextCursor, }) render() { const query = this.projects() return html` ` } } ``` ``` -------------------------------- ### Configure useMutation with a scope id to serialize mutations Source: https://github.com/tanstack/query/blob/main/docs/framework/react/guides/mutations.md By default all mutations run in parallel, even repeated calls to the same mutation. Giving mutations the same scope.id runs them in serial: a triggered mutation starts in isPaused: true if another mutation for that scope is in progress, is queued, and resumes automatically when its turn comes. ```tsx const mutation = useMutation({ mutationFn: addTodo, scope: { id: 'todo', }, }) ``` -------------------------------- ### Install @tanstack/svelte-query with yarn Source: https://github.com/tanstack/query/blob/main/docs/framework/svelte/installation.md Installs Svelte Query via yarn as an alternative to npm. ```sh yarn add @tanstack/svelte-query ``` -------------------------------- ### Lit Query quick start with createQueryController and createMutationController Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/quick-start.md Shows the three core Lit Query concepts: queries, mutations, and query invalidation. The controllers are created with `this` because a `LitElement` is a `ReactiveControllerHost`; Lit Query uses the host lifecycle to subscribe, request updates, and clean up when the element disconnects. Mount the provider around your component as shown in the HTML snippet. ```ts import { QueryClient, QueryClientProvider, createMutationController, createQueryController, } from '@tanstack/lit-query' import { LitElement, html } from 'lit' import { addTodo, getTodos } from './api' const queryClient = new QueryClient() class AppQueryProvider extends QueryClientProvider { constructor() { super() this.client = queryClient } } customElements.define('app-query-provider', AppQueryProvider) class TodosView extends LitElement { private readonly todos = createQueryController(this, { queryKey: ['todos'], queryFn: getTodos, }) private readonly createTodo = createMutationController(this, { mutationFn: addTodo, onSuccess: async () => { await queryClient.invalidateQueries({ queryKey: ['todos'] }) }, }) render() { const query = this.todos() const mutation = this.createTodo() if (query.isPending) return html`Loading...` if (query.isError) return html`Error: ${query.error.message}` return html`
    ${query.data.map((todo) => html`
  • ${todo.title}
  • `)}
` } } customElements.define('todos-view', TodosView) ``` ```html ``` -------------------------------- ### Install @tanstack/svelte-query with pnpm Source: https://github.com/tanstack/query/blob/main/docs/framework/svelte/installation.md Installs Svelte Query via pnpm as an alternative to npm. ```sh pnpm add @tanstack/svelte-query ``` -------------------------------- ### Enable and prepare pnpm via corepack Source: https://github.com/tanstack/query/blob/main/CONTRIBUTING.md Run if you encounter pnpm-related issues to enable corepack and prepare the pinned package manager. ```bash corepack enable && corepack prepare ``` -------------------------------- ### Install @tanstack/vue-query with bun Source: https://github.com/tanstack/query/blob/main/docs/framework/vue/installation.md Alternative package manager install of Vue Query using bun. ```sh bun add @tanstack/vue-query ``` -------------------------------- ### Install @tanstack/vue-query with yarn Source: https://github.com/tanstack/query/blob/main/docs/framework/vue/installation.md Alternative package manager install of Vue Query using yarn. ```sh yarn add @tanstack/vue-query ``` -------------------------------- ### Pass options as a function to useQuery in Solid Query Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/quick-start.md Solid Query primitives like useQuery, useMutation, and useIsFetching take arguments as functions so they can be tracked in a reactive scope. The React-style object argument is shown as incorrect. ```tsx // ❌ react version useQuery({ queryKey: ['todos', todo], queryFn: fetchTodos, }) // ✅ solid version useQuery(() => ({ queryKey: ['todos', todo], queryFn: fetchTodos, })) ``` -------------------------------- ### Install @tanstack/vue-query with pnpm Source: https://github.com/tanstack/query/blob/main/docs/framework/vue/installation.md Alternative package manager install of Vue Query using pnpm. ```sh pnpm add @tanstack/vue-query ``` -------------------------------- ### Using useQuery in a component with prefetched and client-only queries Source: https://github.com/tanstack/query/blob/main/docs/framework/preact/guides/ssr.md Shows how to use useQuery inside a component. The first query is prefetched on the server and available immediately; the second is not prefetched and will fetch on the client. Both patterns can be mixed. ```tsx function Posts() { // This useQuery could just as well happen in some deeper child to , // 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, }) // ... } ``` -------------------------------- ### Install @tanstack/solid-query with yarn Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/installation.md Installs Solid Query using yarn as an alternative package manager. ```sh yarn add @tanstack/solid-query ``` -------------------------------- ### Install @tanstack/solid-query with pnpm Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/installation.md Installs Solid Query using pnpm as an alternative package manager. ```sh pnpm add @tanstack/solid-query ``` -------------------------------- ### Set up QueryClientProvider in Svelte Source: https://github.com/tanstack/query/blob/main/docs/framework/svelte/quick-start.md Wrap your app with QueryClientProvider and pass a QueryClient instance to provide the query client to all components. ```svelte ``` -------------------------------- ### Set up QueryClientProvider for Server Components in Next.js Source: https://github.com/tanstack/query/blob/main/docs/framework/react/guides/advanced-ssr.md Create a QueryClient and wrap the app in QueryClientProvider for Server Components. In Next.js, split into app/providers.tsx and app/layout.tsx. The providers file must have 'use client' at the top. ```tsx // In Next.js, this file would be called: app/providers.tsx 'use client' // Since QueryClientProvider relies on useContext under the hood, we have to put 'use client' on top import { environmentManager, QueryClient, QueryClientProvider, } from '@tanstack/react-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, }, }, }) } let browserQueryClient: QueryClient | undefined = undefined function getQueryClient() { if (environmentManager.isServer()) { // Server: always make a new query client return makeQueryClient() } else { // Browser: make a new query client if we don't already have one // This is very important, so we don't re-make a new client if React // suspends during the initial render. This may not be needed if we // have a suspense boundary BELOW the creation of the query client if (!browserQueryClient) browserQueryClient = makeQueryClient() return browserQueryClient } } export default function Providers({ children }: { children: React.ReactNode }) { // NOTE: Avoid useState when initializing the query client if you don't // have a suspense boundary between this and the code that may // suspend because React will throw away the client on the initial // render if it suspends and there is no boundary const queryClient = getQueryClient() return ( {children} ) } ``` ```tsx // In Next.js, this file would be called: app/layout.tsx import Providers from './providers' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( {children} ) } ``` -------------------------------- ### Run tests for @tanstack/react-query with pnpm nx run Source: https://github.com/tanstack/query/blob/main/CONTRIBUTING.md Example of running the test:lib target for the react-query package. Run from the root folder, not inside the package folder. ```bash pnpm nx run @tanstack/react-query:test:lib ``` -------------------------------- ### Install @tanstack/react-query with yarn Source: https://github.com/tanstack/query/blob/main/docs/framework/react/installation.md Install React Query using yarn as an alternative package manager. ```sh yarn add @tanstack/react-query ``` -------------------------------- ### Install @tanstack/react-query with pnpm Source: https://github.com/tanstack/query/blob/main/docs/framework/react/installation.md Install React Query using pnpm as an alternative package manager. ```sh pnpm add @tanstack/react-query ``` -------------------------------- ### Prefetch with route.preload using queryClient.query Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/guides/ssr.md Prefetch a query from a SolidStart route's preload function by calling queryClient.query(...). The .catch(noop) prevents a failed prefetch from aborting routing; the failure surfaces later via useQuery. Share the query options object between route.preload and the component to avoid drift. ```tsx import { noop, useQueryClient } from '@tanstack/solid-query' export const route = { preload: () => { const queryClient = useQueryClient() queryClient.query(postsQueryOptions()).catch(noop) }, } export default function Posts() { const query = useQuery(() => postsQueryOptions()) // ... } ``` -------------------------------- ### reset() example Source: https://github.com/tanstack/query/blob/main/docs/framework/angular/reference/classes/MutationObserver.md Example of calling reset on an observer. ```ts observer.reset() ```