### React Native Example Setup Commands Source: https://github.com/tanstack/query/blob/main/examples/react/react-native/README.md These commands guide you through setting up and running the React Native example project using Expo CLI and pnpm. ```bash npm install --global expo-cli ``` ```bash pnpm install ``` ```bash pnpm start ``` -------------------------------- ### Run Specific Example in Development Mode Source: https://github.com/tanstack/query/blob/main/CONTRIBUTING.md Starts the development server for a selected example within its directory. ```bash pnpm run dev ``` -------------------------------- ### Start Documentation Development Server (Bash) Source: https://github.com/tanstack/query/blob/main/CONTRIBUTING.md Initiates the development server for the documentation site from the `/docs` directory during online development setup. ```bash npm run dev ``` -------------------------------- ### Use Composition API with ``` -------------------------------- ### Run TanStack.com Locally for Docs Preview Source: https://github.com/tanstack/query/blob/main/CONTRIBUTING.md Navigates into the tanstack.com directory, installs its dependencies, and starts the development server to preview local documentation changes. ```sh cd tanstack.com pnpm i # The app will run on https://localhost:3000 by default pnpm dev ``` -------------------------------- ### Quick Start with createQueryController in Lit Source: https://github.com/tanstack/query/blob/main/packages/lit-query/README.md This example demonstrates how to set up a QueryClient, define a QueryClientProvider, and use createQueryController within a Lit element to fetch and display user data. ```ts import { LitElement, html } from 'lit' import { QueryClient, QueryClientProvider, createQueryController, } from '@tanstack/lit-query' 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) ``` -------------------------------- ### Install createAsyncStoragePersister Source: https://github.com/tanstack/query/blob/main/docs/framework/react/plugins/createAsyncStoragePersister.md Install the `@tanstack/query-async-storage-persister` and `@tanstack/react-query-persist-client` packages using your preferred package manager. ```bash npm install @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` ```bash pnpm add @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` ```bash yarn add @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` ```bash bun add @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` -------------------------------- ### Basic TanStack Query with SolidJS Example Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/quick-start.md This snippet demonstrates the basic setup and usage of useQuery with QueryClientProvider in a SolidJS application to fetch and render data, handling pending, error, and success states. ```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 ( ) } ``` -------------------------------- ### Install @tanstack/query-persist-client-core Source: https://github.com/tanstack/query/blob/main/docs/framework/react/plugins/createPersister.md Use one of these commands to install the `@tanstack/query-persist-client-core` package, which provides the `experimental_createQueryPersister` utility. ```bash npm install @tanstack/query-persist-client-core ``` ```bash pnpm add @tanstack/query-persist-client-core ``` ```bash yarn add @tanstack/query-persist-client-core ``` ```bash bun add @tanstack/query-persist-client-core ``` -------------------------------- ### Run Lit Examples from Repository Source: https://github.com/tanstack/query/blob/main/packages/lit-query/README.md These commands launch the various Lit example applications included in the repository for demonstration and testing purposes. ```bash pnpm --dir examples/lit/basic run dev ``` ```bash pnpm --dir examples/lit/pagination run dev ``` ```bash pnpm --dir examples/lit/ssr run dev ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/tanstack/query/blob/main/examples/solid/astro/README.md Run this command to install all necessary project dependencies defined in `package.json`. ```sh npm install ``` -------------------------------- ### Fetching GitHub Repository Data with Solid Query Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/overview.md This example illustrates the basic setup and usage of `useQuery` in Solid Query to fetch data from the GitHub API. It integrates `ErrorBoundary` for error handling and `Suspense` for managing loading states. ```tsx import { ErrorBoundary, Suspense } from 'solid-js' import { useQuery, QueryClient, QueryClientProvider, } from '@tanstack/solid-query' function App() { const repositoryQuery = useQuery(() => ({ queryKey: ['TanStack Query'], queryFn: async () => { const result = await fetch('https://api.github.com/repos/TanStack/query') if (!result.ok) throw new Error('Failed to fetch data') return result.json() }, staleTime: 1000 * 60 * 5, // 5 minutes throwOnError: true, // Throw an error if the query fails })) return (
Static Content
{/* An error while fetching will be caught by the ErrorBoundary */} Something went wrong!
}> {/* Suspense will trigger a loading state while the data is being fetched */} Loading...}> {/* The `data` property on a query is a SolidJS resource so it will work with Suspense and transitions out of the box! */}
{repositoryQuery.data?.updated_at}
) } const root = document.getElementById('root') const client = new QueryClient() render( () => ( ), root!, ) ``` -------------------------------- ### Start development server Source: https://github.com/tanstack/query/blob/main/examples/vue/nuxt3/README.md Run this command to start the development server for the Nuxt 3 application, accessible at http://localhost:3000. ```bash pnpm dev ``` -------------------------------- ### Start Auto-Build in Root Directory (Bash) Source: https://github.com/tanstack/query/blob/main/CONTRIBUTING.md Runs the auto-build process for the TanStack Query project from the root directory during online development setup. ```bash npm start ``` -------------------------------- ### Install Lit Query with bun Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/installation.md Use bun to install the Lit Query adapter, TanStack Query Core, and Lit. ```bash bun add @tanstack/lit-query @tanstack/query-core lit ``` -------------------------------- ### Run Lit Examples with Custom Ports Source: https://github.com/tanstack/query/blob/main/packages/lit-query/README.md These commands show how to run the Lit examples while specifying custom port numbers or host configurations using environment variables. ```bash DEMO_PORT=4180 pnpm --dir examples/lit/basic run dev ``` ```bash PAGINATION_DEMO_PORT=4181 PAGINATION_API_PORT=4182 pnpm --dir examples/lit/pagination run dev ``` ```bash SSR_PORT=4180 pnpm --dir examples/lit/ssr run dev ``` ```bash SSR_HOST=0.0.0.0 pnpm --dir examples/lit/ssr run dev ``` -------------------------------- ### Starting the Svelte development server Source: https://github.com/tanstack/query/blob/main/examples/svelte/load-more-infinite-scroll/README.md Run these commands to start the development server, with an option to automatically open the app in a new browser tab. ```bash npm run dev # or start the server and open the app in a new browser tab npm run dev -- --open ``` -------------------------------- ### Install Lit Query with npm Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/installation.md Use npm to install the Lit Query adapter, TanStack Query Core, and Lit. ```bash npm i @tanstack/lit-query @tanstack/query-core lit ``` -------------------------------- ### LitElement Example Using createQueriesController Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/reference/functions/createQueriesController.md This example demonstrates how to use `createQueriesController` within a LitElement to manage multiple queries and combine their results for rendering. ```typescript import { LitElement, html } from 'lit' import { createQueriesController } from '@tanstack/lit-query' class DashboardView extends LitElement { private readonly dashboard = createQueriesController(this, { queries: [ { queryKey: ['stats'], queryFn: fetchStats }, { queryKey: ['projects'], queryFn: fetchProjects }, ], combine: ([stats, projects]) => ({ stats: stats.data, projects: projects.data ?? [], isPending: stats.isPending || projects.isPending, }), }) render() { const dashboard = this.dashboard() return html`

Projects: ${dashboard.projects.length}

` } } ``` -------------------------------- ### Install Project Dependencies with pnpm Source: https://github.com/tanstack/query/blob/main/CONTRIBUTING.md Installs all required project dependencies using pnpm. Run this command after forking and cloning the repository. ```bash pnpm install ``` -------------------------------- ### Start the Svelte development server Source: https://github.com/tanstack/query/blob/main/examples/svelte/basic/README.md Run `npm run dev` to start the development server. Add `-- --open` to automatically open the application in a new browser tab. ```bash npm run dev ``` ```bash # or start the server and open the app in a new browser tab npm run dev -- --open ``` -------------------------------- ### Install Lit Query with yarn Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/installation.md Use yarn to install the Lit Query adapter, TanStack Query Core, and Lit. ```bash yarn add @tanstack/lit-query @tanstack/query-core lit ``` -------------------------------- ### Example Usage of createQueryController in LitElement Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/reference/functions/createQueryController.md This example demonstrates how to integrate `createQueryController` into a LitElement to fetch and render a list of todos, including handling loading and error states. ```ts import { LitElement, html } from 'lit' import { createQueryController } from '@tanstack/lit-query' class TodosView extends LitElement { private readonly todos = createQueryController(this, { queryKey: ['todos'], queryFn: async () => fetch('/api/todos').then((r) => r.json()), }) render() { const query = this.todos() if (query.isPending) return html`Loading...` if (query.isError) return html`Error` return html`` } } ``` -------------------------------- ### Install Preact Query Devtools Source: https://github.com/tanstack/query/blob/main/docs/framework/preact/devtools.md Install the Preact Query Devtools package using your preferred package manager. ```bash npm i @tanstack/preact-query-devtools ``` ```bash pnpm add @tanstack/preact-query-devtools ``` ```bash yarn add @tanstack/preact-query-devtools ``` ```bash bun add @tanstack/preact-query-devtools ``` -------------------------------- ### Install Lit Query with pnpm Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/installation.md Use pnpm to install the Lit Query adapter, TanStack Query Core, and Lit. ```bash pnpm add @tanstack/lit-query @tanstack/query-core lit ``` -------------------------------- ### 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 necessary packages using npm, pnpm, yarn, or bun to enable synchronous storage persistence for Tanstack Query. ```bash npm install @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` ```bash pnpm add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` ```bash yarn add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` ```bash bun add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` -------------------------------- ### Install Angular Query package Source: https://github.com/tanstack/query/blob/main/packages/angular-query-experimental/README.md Install the `@tanstack/angular-query-experimental` package using your preferred package manager. ```bash $ npm i @tanstack/angular-query-experimental ``` ```bash $ pnpm add @tanstack/angular-query-experimental ``` ```bash $ yarn add @tanstack/angular-query-experimental ``` ```bash $ bun add @tanstack/angular-query-experimental ``` -------------------------------- ### Configure QueryClient with experimental_createQueryPersister Source: https://github.com/tanstack/query/blob/main/docs/framework/react/plugins/createPersister.md This example demonstrates how to initialize `experimental_createQueryPersister` with `AsyncStorage` and apply it globally to all queries via `QueryClient`'s `defaultOptions`. ```tsx import AsyncStorage from '@react-native-async-storage/async-storage' import { QueryClient } from '@tanstack/react-query' import { experimental_createQueryPersister } from '@tanstack/query-persist-client-core' const persister = experimental_createQueryPersister({ storage: AsyncStorage, maxAge: 1000 * 60 * 60 * 12 // 12 hours }) const queryClient = new QueryClient({ defaultOptions: { queries: { gcTime: 1000 * 30, // 30 seconds persister: persister.persisterFn } } }) ``` -------------------------------- ### Local Development Setup for @tanstack/lit-query Source: https://github.com/tanstack/query/blob/main/packages/lit-query/README.md These commands are for setting up and building the @tanstack/lit-query package during local development within the repository. ```bash pnpm install ``` ```bash pnpm --dir packages/lit-query run build ``` -------------------------------- ### Install React Query Devtools Source: https://github.com/tanstack/query/blob/main/docs/framework/react/devtools.md Install the React Query Devtools package using your preferred package manager. For Next.js 13+ App Dir, install as a dev dependency. ```bash npm i @tanstack/react-query-devtools ``` ```bash pnpm add @tanstack/react-query-devtools ``` ```bash yarn add @tanstack/react-query-devtools ``` ```bash bun add @tanstack/react-query-devtools ``` -------------------------------- ### Install @tanstack/lit-query with npm Source: https://github.com/tanstack/query/blob/main/packages/lit-query/README.md Use this command to install the @tanstack/lit-query package along with its core dependencies. ```bash npm install @tanstack/lit-query @tanstack/query-core lit ``` -------------------------------- ### Install Solid Query Devtools Package Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/devtools.md Install the Solid Query Devtools package using your preferred Node.js package manager. ```bash npm i @tanstack/solid-query-devtools ``` ```bash pnpm add @tanstack/solid-query-devtools ``` ```bash yarn add @tanstack/solid-query-devtools ``` ```bash bun add @tanstack/solid-query-devtools ``` -------------------------------- ### Install ESLint Plugin Query Source: https://github.com/tanstack/query/blob/main/docs/framework/react/installation.md Install the ESLint plugin for React Query as a development dependency to help catch bugs and inconsistencies while coding. ```bash npm i -D @tanstack/eslint-plugin-query ``` ```bash pnpm add -D @tanstack/eslint-plugin-query ``` ```bash yarn add -D @tanstack/eslint-plugin-query ``` ```bash bun add -D @tanstack/eslint-plugin-query ``` -------------------------------- ### Run Development Server for TanStack Query Source: https://github.com/tanstack/query/blob/main/CONTRIBUTING.md Starts the development server in watch mode, allowing for live reloading during general development. ```bash pnpm run watch ``` -------------------------------- ### Run Next.js Development Server Source: https://github.com/tanstack/query/blob/main/examples/react/nextjs-app-prefetching/README.md Execute one of these commands in your terminal to start the Next.js development server locally. ```bash npm run dev # or yarn dev # or pnpm dev ``` -------------------------------- ### Run Next.js Development Server Source: https://github.com/tanstack/query/blob/main/integrations/react-next-15/README.md Use these commands to start the development server for a Next.js application, allowing you to view and edit pages locally. ```bash npm run dev ``` ```bash yarn dev ``` ```bash pnpm dev ``` -------------------------------- ### Install Svelte Query Devtools Source: https://github.com/tanstack/query/blob/main/docs/framework/svelte/devtools.md Use these commands to add the Svelte Query Devtools package to your project using different package managers. ```bash npm i @tanstack/svelte-query-devtools ``` ```bash pnpm add @tanstack/svelte-query-devtools ``` ```bash yarn add @tanstack/svelte-query-devtools ``` ```bash bun add @tanstack/svelte-query-devtools ``` -------------------------------- ### Initialize a New SolidStart Project Source: https://github.com/tanstack/query/blob/main/examples/solid/solid-start-streaming/README.md Use these commands to create a new SolidStart project, either in the current directory or a specified new directory. ```bash # create a new project in the current directory npm init solid@latest ``` ```bash # create a new project in my-app npm init solid@latest my-app ``` -------------------------------- ### Using createMutationController in a LitElement for Adding Todos Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/reference/functions/createMutationController.md This example demonstrates how to integrate `createMutationController` into a LitElement to handle adding new todo items, showing mutation setup and UI interaction. ```ts import { LitElement, html } from 'lit' import { createMutationController } from '@tanstack/lit-query' class AddTodoForm extends LitElement { private readonly addTodo = createMutationController(this, { mutationFn: (title: string) => fetch('/api/todos', { method: 'POST', body: JSON.stringify({ title }) }), }) render() { const mutation = this.addTodo() return html` ` } } ``` -------------------------------- ### Invalidate Queries by Prefix in TanStack Query Source: https://github.com/tanstack/query/blob/main/docs/framework/react/guides/query-invalidation.md This example demonstrates how to invalidate queries whose keys start with `['todos']`, affecting both the base `todos` query and those with additional subkeys like `{ page: 1 }`. ```tsx import { useQuery, useQueryClient } from '@tanstack/react-query' // Get QueryClient from the context const queryClient = useQueryClient() queryClient.invalidateQueries({ queryKey: ['todos'] }) // Both queries below will be invalidated const todoListQuery = useQuery({ queryKey: ['todos'], queryFn: fetchTodoList, }) const todoListQuery = useQuery({ queryKey: ['todos', { page: 1 }], queryFn: fetchTodoList, }) ``` -------------------------------- ### restoreQueries(queryClient: QueryClient, filters) Source: https://github.com/tanstack/query/blob/main/docs/framework/react/plugins/createPersister.md This function can be used to restore queries that are currently stored by persister. For example when your app is starting up in offline mode, or you want all or only specific data from previous session to be immediately available without intermediate `loading` state. ```APIDOC ## Function: restoreQueries(queryClient: QueryClient, filters) ### Description This function can be used to restore queries that are currently stored by persister. For example when your app is starting up in offline mode, or you want all or only specific data from previous session to be immediately available without intermediate `loading` state. ### Parameters - **queryClient** (QueryClient) - Required - The QueryClient instance. - **filters** (object) - Optional - An object to filter which queries to restore. - **queryKey?** (QueryKey) - Optional - Set this property to define a query key to match on. - **exact?** (boolean) - Optional - If you don't want to search queries inclusively by query key, you can pass the `exact: true` option to return only the query with the exact query key you have passed. ### Returns - **Promise** - A Promise that resolves when the queries have been restored. ``` -------------------------------- ### Prefetching and Hydration with Next.js Pages Router Source: https://github.com/tanstack/query/blob/main/docs/framework/react/guides/advanced-ssr.md This example shows how to prefetch data using `getStaticProps` (or `getServerSideProps`), dehydrate the `QueryClient` state, and then hydrate it on the client using `HydrationBoundary` in a Next.js Pages Router setup. It also demonstrates mixing prefetched and client-side fetched queries. ```tsx // pages/posts.tsx import { dehydrate, HydrationBoundary, QueryClient, useQuery, } from '@tanstack/react-query' // This could also be getServerSideProps export async function getStaticProps() { const queryClient = new QueryClient() await queryClient.prefetchQuery({ queryKey: ['posts'], queryFn: getPosts, }) return { props: { dehydratedState: dehydrate(queryClient), }, } } function Posts() { // This useQuery could just as well happen in some deeper child to // the , data will be available immediately either way // // Note that we are using useQuery here instead of useSuspenseQuery. // Because this data has already been prefetched, there is no need to // ever suspend in the component itself. If we forget or remove the // prefetch, this will instead fetch the data on the client, while // using useSuspenseQuery would have had worse side effects. 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, }) // ... } export default function PostsRoute({ dehydratedState }) { return ( ) } ``` -------------------------------- ### Setting Up and Using a Global Default Query Function in Solid Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/guides/default-query-function.md This snippet illustrates how to define a `defaultQueryFn` that receives the `queryKey`, configure it within `QueryClient`'s `defaultOptions`, and then use `useQuery` with only a `queryKey` to leverage the global function. It also shows how to combine the default function with additional `useQuery` options. ```tsx // Define a default query function that will receive the query key const defaultQueryFn = async ({ queryKey }) => { const { data } = await axios.get( `https://jsonplaceholder.typicode.com${queryKey[0]}`, ) return data } // provide the default query function to your app with defaultOptions const queryClient = new QueryClient({ defaultOptions: { queries: { queryFn: defaultQueryFn, }, }, }) function App() { return ( ) } // All you have to do now is pass a key! function Posts() { const postsQuery = useQuery(() => ({ queryKey: ['/posts'] })) // ... } // You can even leave out the queryFn and just go straight into options function Post(props) { const postQuery = useQuery(() => ({ queryKey: [`/posts/${props.postId}`], enabled: !!props.postId, })) // ... } ``` -------------------------------- ### createQueriesController(host, options, queryClient?) Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/reference/functions/createQueriesController.md Creates a Lit reactive controller that subscribes the host to multiple queries. The returned accessor is callable and also exposes `current` and `destroy`. When `options` or `options.queries` is a function, it is re-read during host updates so the query list can follow reactive host state. If `queryClient` is omitted, the controller resolves the client from the nearest connected `QueryClientProvider`. ```APIDOC ## createQueriesController() ### Description Creates a Lit reactive controller that subscribes the host to multiple queries. The returned accessor is callable and also exposes `current` and `destroy`. When `options` or `options.queries` is a function, it is re-read during host updates so the query list can follow reactive host state. If `queryClient` is omitted, the controller resolves the client from the nearest connected `QueryClientProvider`. ### Function Signature ```ts function createQueriesController( host, options, queryClient?): QueriesResultAccessor; ``` ### Type Parameters - **TQueryOptions** (extends `any`[]) - **TCombinedResult** (= `CreateQueriesResults`\<`TQueryOptions`\>) ### Parameters - **host** (`ReactiveControllerHost`) - The Lit reactive controller host that owns the queries subscription. - **options** ([`Accessor`](../type-aliases/Accessor.md)\<[`CreateQueriesControllerOptions`](../type-aliases/CreateQueriesControllerOptions.md)\<`TQueryOptions`, `TCombinedResult`\>\>) - Queries controller 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 [`QueriesResultAccessor`](../type-aliases/QueriesResultAccessor.md)\<`TCombinedResult`\> - An accessor for the latest query results, or the value returned by `combine`. ### Example ```ts import { LitElement, html } from 'lit' import { createQueriesController } from '@tanstack/lit-query' class DashboardView extends LitElement { private readonly dashboard = createQueriesController(this, { queries: [ { queryKey: ['stats'], queryFn: fetchStats }, { queryKey: ['projects'], queryFn: fetchProjects }, ], combine: ([stats, projects]) => ({ stats: stats.data, projects: projects.data ?? [], isPending: stats.isPending || projects.isPending, }), }) render() { const dashboard = this.dashboard() return html`

Projects: ${dashboard.projects.length}

` } } ``` ``` -------------------------------- ### Basic Usage: Persist QueryClient to localStorage Source: https://github.com/tanstack/query/blob/main/docs/framework/react/plugins/createSyncStoragePersister.md This example shows how to initialize a `QueryClient`, create a `createSyncStoragePersister` instance using `window.localStorage`, and then pass it to `persistQueryClient` to enable state persistence. ```tsx import { persistQueryClient } from '@tanstack/react-query-persist-client' import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister' const queryClient = new QueryClient({ defaultOptions: { queries: { gcTime: 1000 * 60 * 60 * 24, // 24 hours }, }, }) const localStoragePersister = createSyncStoragePersister({ storage: window.localStorage, }) // const sessionStoragePersister = createSyncStoragePersister({ storage: window.sessionStorage }) persistQueryClient({ queryClient, persister: localStoragePersister, }) ``` -------------------------------- ### Install TanStack Query ESLint Plugin Source: https://github.com/tanstack/query/blob/main/docs/eslint/eslint-plugin-query.md Install the ESLint plugin as a development dependency using your preferred package manager. ```bash npm i -D @tanstack/eslint-plugin-query ``` ```bash pnpm add -D @tanstack/eslint-plugin-query ``` ```bash yarn add -D @tanstack/eslint-plugin-query ``` ```bash bun add -D @tanstack/eslint-plugin-query ``` -------------------------------- ### Preview Production Build Locally Source: https://github.com/tanstack/query/blob/main/examples/solid/astro/README.md Allows for a local preview of the built production site before deployment, ensuring everything works as expected. ```sh npm run preview ``` -------------------------------- ### Create New Astro Minimal Project Source: https://github.com/tanstack/query/blob/main/examples/solid/astro/README.md Use this command to initialize a new Astro project with the minimal template. ```sh npm create astro@latest -- --template minimal ``` -------------------------------- ### Start Development Server with Angular CLI Source: https://github.com/tanstack/query/blob/main/integrations/angular-cli-20/README.md Use this command to launch a local development server, making the application accessible in a browser and enabling automatic reloads on file changes. ```bash ng serve ``` -------------------------------- ### Creating a new Svelte project Source: https://github.com/tanstack/query/blob/main/examples/svelte/load-more-infinite-scroll/README.md Use these commands to initialize a new Svelte project, either in the current directory or a specified new directory. ```bash # create a new project in the current directory npm create svelte@latest # create a new project in my-app npm create svelte@latest my-app ``` -------------------------------- ### Configure QueryClient with experimental_createQueryPersister Source: https://github.com/tanstack/query/blob/main/docs/framework/vue/plugins/createPersister.md Create an `experimental_createQueryPersister` instance with a storage and `maxAge`, then apply its `persisterFn` to the `defaultOptions.queries` of your `QueryClient`. ```tsx import { QueryClient } from '@tanstack/vue-query' import { experimental_createQueryPersister } from '@tanstack/query-persist-client-core' const persister = experimental_createQueryPersister({ storage: AsyncStorage, maxAge: 1000 * 60 * 60 * 12, // 12 hours }) const queryClient = new QueryClient({ defaultOptions: { queries: { gcTime: 1000 * 30, // 30 seconds persister: persister.persisterFn, }, }, }) ``` -------------------------------- ### Basic Article and Comments Components in Solid.js Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/guides/prefetching.md Illustrates basic data fetching for an article and its comments using `useQuery` in Solid.js components without explicit prefetching. ```tsx import { Switch, Match } from 'solid-js' function Article(props) { const articleQuery = useQuery(() => ({ queryKey: ['article', props.id], queryFn: getArticleById, })) return ( Loading article... ) } function Comments(props) { const commentsQuery = useQuery(() => ({ queryKey: ['article-comments', props.id], queryFn: getArticleCommentsById, })) ... } ``` -------------------------------- ### Install TanStack Angular Query Source: https://github.com/tanstack/query/blob/main/docs/framework/angular/installation.md Use one of the following commands to install the experimental TanStack Angular Query library, compatible with Angular v16 and higher. ```bash npm i @tanstack/angular-query-experimental ``` ```bash pnpm add @tanstack/angular-query-experimental ``` ```bash yarn add @tanstack/angular-query-experimental ``` ```bash bun add @tanstack/angular-query-experimental ``` -------------------------------- ### createQueryController() Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/reference/functions/createQueryController.md Creates a Lit reactive controller that subscribes the host to a single query. The returned accessor is callable and also exposes `current`, `refetch`, `suspense`, 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 ## Function: createQueryController() ### Description Creates a Lit reactive controller that subscribes the host to a single query. The returned accessor is callable and also exposes `current`, `refetch`, `suspense`, 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`. ### Signature ```ts function createQueryController( host, options, queryClient?): QueryResultAccessor; ``` ### Type Parameters - **TQueryFnData** (`unknown`) - **TError** (`Error`) - **TData** (`TQueryFnData`) - **TQueryData** (`TQueryFnData`) - **TQueryKey** (`readonly unknown[]`) ### Parameters - **host** (`ReactiveControllerHost`) - The Lit reactive controller host that owns the query subscription. - **options** (`Accessor>`) - 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 - (`QueryResultAccessor`) - An accessor for the latest query result with query helper methods. ### Example ```ts import { LitElement, html } from 'lit' import { createQueryController } from '@tanstack/lit-query' class TodosView extends LitElement { private readonly todos = createQueryController(this, { queryKey: ['todos'], queryFn: async () => fetch('/api/todos').then((r) => r.json()), }) render() { const query = this.todos() if (query.isPending) return html`Loading...` if (query.isError) return html`Error` return html`
    ${query.data.map((todo) => html`
  • ${todo.title}
  • `)}
` } } ``` ``` -------------------------------- ### Install React Hooks Testing Library Source: https://github.com/tanstack/query/blob/main/docs/framework/react/guides/testing.md Installs `@testing-library/react-hooks` and `react-test-renderer` for testing React Query hooks in React 17 or earlier. `react-test-renderer` is a required peer dependency. ```sh npm install @testing-library/react-hooks react-test-renderer --save-dev ``` -------------------------------- ### Basic useQuery Usage in Solid Query Source: https://github.com/tanstack/query/blob/main/docs/framework/solid/reference/useQuery.md This example demonstrates the fundamental use of `useQuery` to fetch data from an API and display loading, error, and success states in a SolidJS component. ```tsx import { useQuery } from '@tanstack/solid-query' function App() { const todos = useQuery(() => ({ queryKey: 'todos', queryFn: async () => { const response = await fetch('/api/todos') if (!response.ok) { throw new Error('Failed to fetch todos') } return response.json() }, })) return (
Error: {todos.error.message}
Loading...
Todos:
    {(todo) =>
  • {todo.title}
  • }
) } ``` -------------------------------- ### Basic Vue Query Component Example Source: https://github.com/tanstack/query/blob/main/docs/framework/vue/quick-start.md This example demonstrates how to use `useQuery` for data fetching, `useMutation` for data updates, and `useQueryClient` for invalidating queries in a Vue 3 component. ```vue ``` -------------------------------- ### Define Lit Component with createMutationController Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/guides/mutations.md This example demonstrates how to set up a Lit component (TodosView) using createMutationController for adding todos and createQueryController for fetching them. It includes onSuccess to invalidate queries after a successful mutation. ```ts import { LitElement, html } from 'lit' import { QueryClient, QueryClientProvider, createMutationController, createQueryController, } from '@tanstack/lit-query' 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: fetchTodos, }) private readonly addTodo = createMutationController(this, { mutationFn: createTodo, onSuccess: async () => { await queryClient.invalidateQueries({ queryKey: ['todos'] }) }, }) render() { const query = this.todos() const mutation = this.addTodo() const todos = query.data ?? [] return html` ${mutation.isError ? html`

${mutation.error.message}

` : null} ${mutation.isSuccess ? html`

Todo added

` : null}
    ${todos.map((todo) => html`
  • ${todo.title}
  • `)}
` } } customElements.define('todos-view', TodosView) ``` -------------------------------- ### Create a new Svelte project using npm Source: https://github.com/tanstack/query/blob/main/examples/svelte/basic/README.md Use `npm create svelte@latest` to initialize a new Svelte project. Specify a directory name to create it in a new folder, or omit it to use the current directory. ```bash # create a new project in the current directory npm create svelte@latest ``` ```bash # create a new project in my-app npm create svelte@latest my-app ``` -------------------------------- ### Example Query Keys Matching a Prefix (TypeScript) Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/guides/query-invalidation.md These examples illustrate how different query keys can match a common prefix, demonstrating which keys would be affected by a prefix-based invalidation. ```ts const projectsListKey = ['projects'] const projectsPageKey = ['projects', 1, 250, false] ``` -------------------------------- ### Implement Lit Query with Queries and Mutations in LitElement Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/quick-start.md This comprehensive example demonstrates how to set up a QueryClientProvider, define a query to fetch data, and a mutation to update data within a LitElement. It includes rendering logic for loading, error, and data states, and shows how to invalidate queries upon successful mutations. ```ts import { LitElement, html } from 'lit' import { QueryClient, QueryClientProvider, createMutationController, createQueryController, } from '@tanstack/lit-query' 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) ``` -------------------------------- ### Define Vue Props in Script Setup Source: https://github.com/tanstack/query/blob/main/docs/framework/vue/reactivity.md This snippet shows how to define component props using `defineProps` in a Vue 3 ` ``` -------------------------------- ### Initialize broadcastQueryClient with QueryClient Source: https://github.com/tanstack/query/blob/main/docs/framework/react/plugins/broadcastQueryClient.md This snippet demonstrates how to import and initialize `broadcastQueryClient` with a `QueryClient` instance, optionally specifying a `broadcastChannel` name for communication between tabs. ```tsx import { broadcastQueryClient } from '@tanstack/query-broadcast-client-experimental' const queryClient = new QueryClient() broadcastQueryClient({ queryClient, broadcastChannel: 'my-app', }) ``` -------------------------------- ### Get Number of Fetching Queries with useIsFetching (React) Source: https://github.com/tanstack/query/blob/main/docs/framework/react/reference/useIsFetching.md Use `useIsFetching` to get the total number of active queries or filter by `queryKey` to count specific queries, useful for global loading indicators. ```tsx import { useIsFetching } from '@tanstack/react-query' // How many queries are fetching? const isFetching = useIsFetching() // How many queries matching the posts prefix are fetching? const isFetchingPosts = useIsFetching({ queryKey: ['posts'] }) ``` -------------------------------- ### Build application for production Source: https://github.com/tanstack/query/blob/main/examples/vue/nuxt3/README.md Execute this command to build the Nuxt 3 application for production deployment. ```bash pnpm build ``` -------------------------------- ### Install Vue Query Devtools Package Source: https://github.com/tanstack/query/blob/main/docs/framework/vue/devtools.md Install the dedicated devtools package for Vue Query using your preferred package manager. This package is designed for Vue 3 and is only included in development builds by default. ```bash npm i @tanstack/vue-query-devtools ``` ```bash pnpm add @tanstack/vue-query-devtools ``` ```bash yarn add @tanstack/vue-query-devtools ``` ```bash bun add @tanstack/vue-query-devtools ``` -------------------------------- ### mutateAsync Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/reference/type-aliases/MutationResultAccessor.md Starts the mutation and returns the observer promise. Rejects if no `QueryClient` can be resolved. ```APIDOC ## mutateAsync ### Description Starts the mutation and returns the observer promise. Rejects if no `QueryClient` can be resolved. ### Property Signature ```ts mutateAsync: MutationObserverResult["mutate"]; ``` ``` -------------------------------- ### MutationResultAccessor mutateAsync Property Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/reference/type-aliases/MutationResultAccessor.md Starts the mutation and returns the observer promise. Rejects if no `QueryClient` can be resolved. ```ts mutateAsync: MutationObserverResult["mutate"]; ``` -------------------------------- ### Basic Usage with PersistQueryClientProvider Source: https://github.com/tanstack/query/blob/main/docs/framework/react/plugins/createAsyncStoragePersister.md This example demonstrates how to import `createAsyncStoragePersister`, configure it with `AsyncStorage` (e.g., from React Native), and wrap your application with `PersistQueryClientProvider` to enable query persistence. ```tsx import AsyncStorage from '@react-native-async-storage/async-storage' import { QueryClient } from '@tanstack/react-query' import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client' import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister' const queryClient = new QueryClient({ defaultOptions: { queries: { gcTime: 1000 * 60 * 60 * 24 // 24 hours } } }) const asyncStoragePersister = createAsyncStoragePersister({ storage: AsyncStorage }) const Root = () => ( ) export default Root ``` -------------------------------- ### mutate(variables, options?) Source: https://github.com/tanstack/query/blob/main/docs/framework/lit/reference/type-aliases/MutationResultAccessor.md Starts the mutation and swallows the returned promise. Throws synchronously if no `QueryClient` can be resolved. ```APIDOC ## mutate(variables, options?) ### Description Starts the mutation and swallows the returned promise. Throws synchronously if no `QueryClient` can be resolved. ### Method Signature ```ts mutate: (variables, options?) => void; ``` ### Parameters - **variables** (`TVariables`) - Required - The variables for the mutation. - **options?** (`MutateOptions`) - Optional - Options for the mutation. ### Returns `void` ``` -------------------------------- ### Get Mutation Cache from QueryClient Source: https://github.com/tanstack/query/blob/main/docs/reference/QueryClient.md Use this method to access the mutation cache instance associated with the QueryClient. ```tsx const mutationCache = queryClient.getMutationCache() ```