### Fetch Data with useQuery in ``` -------------------------------- ### React Query Quick Start Example Source: https://tanstack.com/query/latest/docs/framework/react/quick-start.md This example demonstrates the basic usage of useQuery for data fetching, useMutation for data modification, and queryClient.invalidateQueries for cache invalidation in a React application. ```tsx import { useQuery, useMutation, useQueryClient, QueryClient, QueryClientProvider, } from '@tanstack/react-query' 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')) ``` -------------------------------- ### Fetch GitHub Repo Stats with TanStack Query (React) Source: https://tanstack.com/query/latest/docs This example shows how to use `useQuery` to fetch data from a REST API, manage loading and error states, and display the fetched data in a React component. It requires `QueryClient` and `QueryClientProvider` for setup. ```tsx import { QueryClient, QueryClientProvider, useQuery, } from '@tanstack/react-query' const queryClient = new QueryClient() export default function App() { return ( ) } function Example() { const { isPending, error, data } = useQuery({ queryKey: ['repoData'], queryFn: () => fetch('https://api.github.com/repos/TanStack/query').then((res) => res.json(), ), }) if (isPending) return 'Loading...' if (error) return 'An error has occurred: ' + error.message return (

{data.name}

{data.description}

👀 {data.subscribers_count}{' '} ✨ {data.stargazers_count}{' '} 🍴 {data.forks_count}
) } ``` ```tsx import { QueryClient, QueryClientProvider, useQuery, } from '@tanstack/react-query' const queryClient = new QueryClient() export default function App() { return ( ) } function Example() { const { isPending, error, data } = useQuery({ queryKey: ['repoData'], queryFn: () => fetch('https://api.github.com/repos/TanStack/query').then((res) => res.json(), ), }) if (isPending) return 'Loading...' if (error) return 'An error has occurred: ' + error.message return (

{data.name}

{data.description}

👀 {data.subscribers_count}{' '} ✨ {data.stargazers_count}{' '} 🍴 {data.forks_count}
) } ``` -------------------------------- ### Flat Config Recommended Setup Source: https://tanstack.com/query/latest/docs/eslint/eslint-plugin-query.md Enable all recommended rules by spreading the flat/recommended configuration in eslint.config.js. ```js import pluginQuery from '@tanstack/eslint-plugin-query' export default [ ...pluginQuery.configs['flat/recommended'], // Any other config... ] ``` -------------------------------- ### Legacy Config Recommended Setup Source: https://tanstack.com/query/latest/docs/eslint/eslint-plugin-query.md Add the recommended plugin configuration to the extends array in your .eslintrc file. ```json { "extends": ["plugin:@tanstack/query/recommended"] } ``` -------------------------------- ### Install @tanstack/eslint-plugin-query Source: https://tanstack.com/query/latest/docs/eslint/eslint-plugin-query.md Install the 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 ``` -------------------------------- ### Install Nuxt 3 Project Dependencies Source: https://tanstack.com/query/latest/docs/framework/vue/examples/nuxt3 Installs all required project dependencies using pnpm, ensuring the application has the necessary packages to run. ```bash pnpm install ``` -------------------------------- ### Basic Data Fetching with TanStack Query in React Source: https://tanstack.com/query/latest/docs/framework/react/overview This example demonstrates the most basic usage of TanStack Query to fetch data from a GitHub API endpoint and display it within a React component. It shows the setup of QueryClientProvider and the use of the `useQuery` hook. ```tsx import { QueryClient, QueryClientProvider, useQuery, } from '@tanstack/react-query' const queryClient = new QueryClient() export default function App() { return ( ) } function Example() { const { isPending, error, data } = useQuery({ queryKey: ['repoData'], queryFn: () => fetch('https://api.github.com/repos/TanStack/query').then((res) => res.json(), ), }) if (isPending) return 'Loading...' if (error) return 'An error has occurred: ' + error.message return (

{data.name}

{data.description}

👀 {data.subscribers_count}{' '} ✨ {data.stargazers_count}{' '} 🍴 {data.forks_count}
) } ``` -------------------------------- ### Legacy Config Recommended Strict Setup Source: https://tanstack.com/query/latest/docs/eslint/eslint-plugin-query.md Apply the opinionated recommendedStrict configuration for stricter rule enforcement in legacy environments. ```json { "extends": ["plugin:@tanstack/query/recommendedStrict"] } ``` -------------------------------- ### Install React Query via Package Manager Source: https://tanstack.com/query/latest/docs/framework/react/installation.md Use one of these commands to install the @tanstack/react-query package as a project dependency using your preferred package manager. ```bash npm i @tanstack/react-query ``` ```bash pnpm add @tanstack/react-query ``` ```bash yarn add @tanstack/react-query ``` ```bash bun add @tanstack/react-query ``` -------------------------------- ### Legacy Config Custom Setup Source: https://tanstack.com/query/latest/docs/eslint/eslint-plugin-query.md Define the plugin and individual rules manually within the legacy .eslintrc structure. ```json { "plugins": ["@tanstack/query"], "rules": { "@tanstack/query/exhaustive-deps": "error" } } ``` -------------------------------- ### Flat Config Recommended Strict Setup Source: https://tanstack.com/query/latest/docs/eslint/eslint-plugin-query.md Use flat/recommended-strict to enforce best practices more aggressively than the standard recommended set. ```js import pluginQuery from '@tanstack/eslint-plugin-query' export default [ ...pluginQuery.configs['flat/recommended-strict'], // Any other config... ] ``` -------------------------------- ### Install React Query Devtools with bun Source: https://tanstack.com/query/latest/docs/framework/react/devtools.md Use bun to add the React Query Devtools package to your project dependencies. ```bash bun add @tanstack/react-query-devtools ``` -------------------------------- ### Start Nuxt 3 Development Server Source: https://tanstack.com/query/latest/docs/framework/vue/examples/nuxt3 Launches the Nuxt 3 development server, making the application accessible locally for development and testing. ```bash pnpm dev ``` -------------------------------- ### Vue Query Core Concepts Example Source: https://tanstack.com/query/latest/docs/framework/vue/quick-start.md This example demonstrates the basic usage of `useQuery`, `useMutation`, and `queryClient.invalidateQueries` for data fetching, modification, and cache invalidation in a Vue component. ```vue ``` -------------------------------- ### Nuxt 3 Project README Markdown Source: https://tanstack.com/query/latest/docs/framework/vue/examples/nuxt3 Provides an overview of the Nuxt 3 minimal starter, including setup, development, and production instructions within a markdown file. ```markdown # Nuxt 3 Minimal Starter We recommend looking at the [documentation](https://nuxt.com/docs/3.x/getting-started/introduction). ## Setup Make sure to install the dependencies ```bash pnpm install ``` ## Development Start the development server on http://localhost:3000 ```bash pnpm dev ``` ## Production Build the application for production: ```bash pnpm build ``` Check out the [deployment documentation](https://nuxt.com/docs/3.x/getting-started/deployment). ``` -------------------------------- ### Flat Config Custom Setup Source: https://tanstack.com/query/latest/docs/eslint/eslint-plugin-query.md Manually register the plugin and configure specific rules within the flat configuration object. ```js import pluginQuery from '@tanstack/eslint-plugin-query' export default [ { plugins: { '@tanstack/query': pluginQuery, }, rules: { '@tanstack/query/exhaustive-deps': 'error', }, }, // Any other config... ] ``` -------------------------------- ### Install Vue Query Devtools Package Source: https://tanstack.com/query/latest/docs/framework/vue/devtools.md Install the `@tanstack/vue-query-devtools` package using your preferred package manager. This package provides component-based devtools for Vue 3 applications. ```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 ``` -------------------------------- ### Install React Query Devtools with npm Source: https://tanstack.com/query/latest/docs/framework/react/devtools.md Use npm to add the React Query Devtools package to your project dependencies. ```bash npm i @tanstack/react-query-devtools ``` -------------------------------- ### Define a Basic Mutation Source: https://tanstack.com/query/latest/docs/framework/vue/guides/invalidations-from-mutations.md Initial setup for a mutation using `useMutation` to post a new todo item. ```tsx const mutation = useMutation({ mutationFn: postTodo }) ``` -------------------------------- ### Correct property order for useInfiniteQuery Source: https://tanstack.com/query/latest/docs/eslint/infinite-query-property-order.md This example shows the correct order of `queryFn`, `getPreviousPageParam`, and `getNextPageParam` properties, ensuring proper type inference for infinite queries. ```tsx /* eslint "@tanstack/query/infinite-query-property-order": "warn" */ import { useInfiniteQuery } from '@tanstack/react-query' const query = useInfiniteQuery({ queryKey: ['projects'], queryFn: async ({ pageParam }) => { const response = await fetch(`/api/projects?cursor=${pageParam}`) return await response.json() }, initialPageParam: 0, getPreviousPageParam: (firstPage) => firstPage.previousId ?? undefined, getNextPageParam: (lastPage) => lastPage.nextId ?? undefined, maxPages: 3, }) ``` -------------------------------- ### Install React Query Devtools with pnpm Source: https://tanstack.com/query/latest/docs/framework/react/devtools.md Use pnpm to add the React Query Devtools package to your project dependencies. ```bash pnpm add @tanstack/react-query-devtools ``` -------------------------------- ### Install React Query Devtools with yarn Source: https://tanstack.com/query/latest/docs/framework/react/devtools.md Use yarn to add the React Query Devtools package to your project dependencies. ```bash yarn add @tanstack/react-query-devtools ``` -------------------------------- ### Basic Data Fetching with TanStack React Query Source: https://tanstack.com/query/latest/docs/framework/react/examples/simple This example demonstrates how to set up `QueryClientProvider` and use the `useQuery` hook to fetch data from an API, handling loading, error, and success states within a React component. ```typescript import React from 'react' import ReactDOM from 'react-dom/client' import { QueryClient, QueryClientProvider, useQuery, } from '@tanstack/react-query' import { ReactQueryDevtools } from '@tanstack/react-query-devtools' const queryClient = new QueryClient() export default function App() { return ( ) } function Example() { const { isPending, error, data, isFetching } = useQuery({ queryKey: ['repoData'], queryFn: async () => { const response = await fetch( 'https://api.github.com/repos/TanStack/query', ) return await response.json() }, }) if (isPending) return 'Loading...' if (error) return 'An error has occurred: ' + error.message return (

{data.full_name}

{data.description}

👀 {data.subscribers_count}{' '} ✨ {data.stargazers_count}{' '} 🍴 {data.forks_count}
{isFetching ? 'Updating...' : ''}
) } const rootElement = document.getElementById('root') if (!rootElement) throw new Error('Missing #root element') ReactDOM.createRoot(rootElement).render() ``` ```typescript import React from 'react' import ReactDOM from 'react-dom/client' import { QueryClient, QueryClientProvider, useQuery, } from '@tanstack/react-query' import { ReactQueryDevtools } from '@tanstack/react-query-devtools' const queryClient = new QueryClient() export default function App() { return ( ) } function Example() { const { isPending, error, data, isFetching } = useQuery({ queryKey: ['repoData'], queryFn: async () => { const response = await fetch( 'https://api.github.com/repos/TanStack/query', ) return await response.json() }, }) if (isPending) return 'Loading...' if (error) return 'An error has occurred: ' + error.message return (

{data.full_name}

{data.description}

👀 {data.subscribers_count}{' '} ✨ {data.stargazers_count}{' '} 🍴 {data.forks_count}
{isFetching ? 'Updating...' : ''}
) } const rootElement = document.getElementById('root') if (!rootElement) throw new Error('Missing #root element') ReactDOM.createRoot(rootElement).render() ``` -------------------------------- ### Correct useMutation() property order Source: https://tanstack.com/query/latest/docs/eslint/mutation-property-order.md Example showing correct property ordering with onMutate, onError, and onSettled in the required sequence for proper type inference. ```tsx /* eslint "@tanstack/query/mutation-property-order": "warn" */ import { useMutation } from '@tanstack/react-query' const mutation = useMutation({ mutationFn: () => Promise.resolve('success'), onMutate: async () => { results.push('onMutate-async') await sleep(1) return { backup: 'async-data' } }, onError: async () => { results.push('onError-async-start') await sleep(1) results.push('onError-async-end') }, onSettled: () => { results.push('onSettled-promise') return Promise.resolve('also-ignored') // Promise (should be ignored) }, }) ``` -------------------------------- ### Install Vue Query with Package Managers Source: https://tanstack.com/query/latest/docs/framework/vue/installation.md Use these commands to add Vue Query to your project using your preferred package manager. Choose the command that corresponds to your development environment. ```bash npm i @tanstack/vue-query ``` ```bash pnpm add @tanstack/vue-query ``` ```bash yarn add @tanstack/vue-query ``` ```bash bun add @tanstack/vue-query ``` -------------------------------- ### Simulating an Infinite Query API Endpoint Source: https://tanstack.com/query/latest/docs/framework/vue/guides/infinite-queries.md This example illustrates the expected response structure from an API endpoint designed for infinite queries. It shows how paginated data and a `nextCursor` are returned, which is essential for `useInfiniteQuery` to fetch subsequent pages. ```tsx fetch('/api/projects?cursor=0') // { data: [...], nextCursor: 3} fetch('/api/projects?cursor=3') // { data: [...], nextCursor: 6} fetch('/api/projects?cursor=6') // { data: [...], nextCursor: 9} fetch('/api/projects?cursor=9') // { data: [...] } ``` -------------------------------- ### Incorrect property order for useInfiniteQuery Source: https://tanstack.com/query/latest/docs/eslint/infinite-query-property-order.md This example demonstrates an incorrect order of `queryFn`, `getPreviousPageParam`, and `getNextPageParam` properties, which can lead to type inference issues. ```tsx /* eslint "@tanstack/query/infinite-query-property-order": "warn" */ import { useInfiniteQuery } from '@tanstack/react-query' const query = useInfiniteQuery({ queryKey: ['projects'], getNextPageParam: (lastPage) => lastPage.nextId ?? undefined, queryFn: async ({ pageParam }) => { const response = await fetch(`/api/projects?cursor=${pageParam}`) return await response.json() }, initialPageParam: 0, getPreviousPageParam: (firstPage) => firstPage.previousId ?? undefined, maxPages: 3, }) ``` -------------------------------- ### Applying Mutation Filters in TanStack Query Source: https://tanstack.com/query/latest/docs/framework/react/guides/filters.md These examples demonstrate how to check for mutations using `isMutating` with different filter conditions, including mutation key and custom predicates. ```tsx // Get the number of all fetching mutations await queryClient.isMutating() // Filter mutations by mutationKey await queryClient.isMutating({ mutationKey: ['post'] }) // Filter mutations using a predicate function await queryClient.isMutating({ predicate: (mutation) => mutation.state.variables?.id === 1, }) ``` -------------------------------- ### Defining Component Props in Vue Source: https://tanstack.com/query/latest/docs/framework/vue/reactivity.md Illustrates how to define component props using ` ``` -------------------------------- ### Consolidate Error Handling with onSettled (TSX) Source: https://tanstack.com/query/latest/docs/framework/vue/guides/optimistic-updates.md This example shows how to use the onSettled callback to handle both successful and failed mutations in a single place. It can be used as an alternative to separate onError and onSuccess handlers. ```tsx useMutation({ mutationFn: updateTodo, // ... onSettled: async (newTodo, error, variables, onMutateResult, context) => { if (error) { // do something } } }) ``` -------------------------------- ### Example Global State with Server and Client Data (TypeScript) Source: https://tanstack.com/query/latest/docs/framework/vue/guides/does-this-replace-client-state.md Illustrates a typical global state object managed by a client-state library, containing both server-derived data (projects, teams, tasks, users) and client-only state (themeMode, sidebarStatus). ```tsx const globalState = { projects, teams, tasks, users, themeMode, sidebarStatus, } ``` -------------------------------- ### Customizing Devtools Panel Height and Width with Style Source: https://tanstack.com/query/latest/docs/framework/react/devtools.md Apply custom CSS styles to the devtools panel using the `style` prop. This example sets both height and width to 100%. ```typescript { height: '100%', width: '100%' } ``` -------------------------------- ### Implement Dependent Queries with useQueries in Vue Source: https://tanstack.com/query/latest/docs/framework/vue/guides/dependent-queries.md This example shows how to use `useQueries` to create multiple dependent queries. The messages queries are dynamically generated based on user IDs fetched from a previous query. ```tsx // Get the users ids const { data: userIds } = useQuery({ queryKey: ['users'], queryFn: getUsersData, select: (users) => users.map((user) => user.id), }) const queries = computed(() => { return userIds.value.length ? userIds.value.map((id) => { return { queryKey: ['messages', id], queryFn: () => getMessagesByUsers(id), } }) : [] }) // Then get the users messages const usersMessages = useQueries({ queries, }) ``` -------------------------------- ### Applying Query Filters in TanStack Query Source: https://tanstack.com/query/latest/docs/framework/react/guides/filters.md Use these examples to cancel, remove, or refetch queries based on various filter criteria like query key and type. ```tsx // Cancel all queries await queryClient.cancelQueries() // Remove all inactive queries that begin with `posts` in the key queryClient.removeQueries({ queryKey: ['posts'], type: 'inactive' }) // Refetch all active queries await queryClient.refetchQueries({ type: 'active' }) // Refetch all active queries that begin with `posts` in the key await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' }) ``` -------------------------------- ### Example of custom client key internal naming Source: https://tanstack.com/query/latest/docs/framework/vue/guides/custom-client.md This snippet illustrates how a custom `queryClientKey` is internally combined with the default query key as a suffix, though users typically don't need to manage this detail. ```tsx const vueQueryPluginOptions: VueQueryPluginOptions = { queryClientKey: 'Foo', } app.use(VueQueryPlugin, vueQueryPluginOptions) // -> VUE_QUERY_CLIENT:Foo ``` -------------------------------- ### Manually Cancelling Queries in React Source: https://tanstack.com/query/latest/docs/framework/react/guides/query-cancellation.md This example demonstrates how to manually cancel an active query using `queryClient.cancelQueries({ queryKey })`. It also shows how to use `AbortSignal` with `fetch` to ensure the underlying request is also cancelled. ```tsx const query = useQuery({ queryKey: ['todos'], queryFn: async ({ signal }) => { const resp = await fetch('/todos', { signal }) return resp.json() } }) const queryClient = useQueryClient() return ( ) ``` -------------------------------- ### new QueryClient(options) Source: https://tanstack.com/query/latest/docs/reference/QueryClient.md Initializes a new instance of the QueryClient, configuring its associated caches and default behaviors for queries and mutations. ```APIDOC ## CONSTRUCTOR QueryClient(options) ### Description Initializes a new instance of the QueryClient, configuring its associated caches and default behaviors for queries and mutations. This client is the primary interface for managing data fetching and caching. ### Parameters #### Request Body - **queryCache** (QueryCache) - Optional - The query cache instance this client will use. - **mutationCache** (MutationCache) - Optional - The mutation cache instance this client will use. - **defaultOptions** (DefaultOptions) - Optional - An object to define default options for all queries and mutations managed by this client. This can also include defaults for hydration. ### Request Example ```typescript import { QueryClient } from '@tanstack/react-query' const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, }, }, }) ``` ``` -------------------------------- ### Get the mutation cache with getMutationCache Source: https://tanstack.com/query/latest/docs/reference/QueryClient.md Retrieves the mutation cache instance that the QueryClient is currently connected to. ```tsx const mutationCache = queryClient.getMutationCache() ``` -------------------------------- ### Get the query cache with getQueryCache Source: https://tanstack.com/query/latest/docs/reference/QueryClient.md Retrieves the query cache instance that the QueryClient is currently connected to. ```tsx const queryCache = queryClient.getQueryCache() ``` -------------------------------- ### Refetching Queries with QueryClient.refetchQueries Source: https://tanstack.com/query/latest/docs/reference/QueryClient.md Demonstrates various ways to refetch queries using `queryClient.refetchQueries`, including refetching all queries, stale queries, and queries matching specific keys or types. ```tsx // refetch all queries: await queryClient.refetchQueries() // refetch all stale queries: await queryClient.refetchQueries({ stale: true }) // refetch all active queries partially matching a query key: await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' }) // refetch all active queries exactly matching a query key: await queryClient.refetchQueries({ queryKey: ['posts', 1], type: 'active', exact: true, }) ``` -------------------------------- ### Initialize QueryClient and Prefetch Data (TypeScript/React Query) Source: https://tanstack.com/query/latest/docs/reference/QueryClient.md Initializes a new QueryClient instance with default query options, setting staleTime to Infinity. Demonstrates how to use `prefetchQuery` to fetch data for a specific query key before it's needed. ```tsx import { QueryClient } from '@tanstack/react-query' const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, }, }, }) await queryClient.prefetchQuery({ queryKey: ['posts'], queryFn: fetchPosts }) ``` -------------------------------- ### queryClient.getQueryState Source: https://tanstack.com/query/latest/docs/reference/QueryClient.md `getQueryState` is a synchronous function that can be used to get an existing query's state. If the query does not exist, `undefined` will be returned. ```APIDOC ## queryClient.getQueryState ### Description `getQueryState` is a synchronous function that can be used to get an existing query's state. If the query does not exist, `undefined` will be returned. ### Method `queryClient.getQueryState` ### Parameters #### Body Parameters - **queryKey** (QueryKey) - Required - [Query Keys](../framework/react/guides/query-keys.md) ### Request Example ```tsx const state = queryClient.getQueryState(queryKey) console.log(state.dataUpdatedAt) ``` ``` -------------------------------- ### Incorrect Query Key Dependencies in TSX Source: https://tanstack.com/query/latest/docs/eslint/exhaustive-deps.md Examples of code that triggers the exhaustive-deps error due to missing variables in the query key. ```tsx /* eslint "@tanstack/query/exhaustive-deps": "error" */ useQuery({ queryKey: ['todo'], queryFn: () => api.getTodo(todoId), }) const todoQueries = { detail: (id) => ({ queryKey: ['todo'], queryFn: () => api.getTodo(id) }), } ``` -------------------------------- ### Using `useUserProjects` with Plain Values and `ref` Source: https://tanstack.com/query/latest/docs/framework/vue/reactivity.md Demonstrates how the updated `useUserProjects` composable can be used with both non-reactive plain string values and reactive `ref` values, allowing queries to react to changes. ```ts // Fetches the user 1's projects, userId is not expected to change. const { data: projects } = useUserProjects('1') ``` ```ts // Fetches the user 1's projects, queries will react to changes on userId. const userId = ref('1') // Make some changes to userId... // Query re-fetches based on any changes to userId. const { data: projects } = useUserProjects(userId) ``` -------------------------------- ### Consuming a Non-Reactive Vue Query Composable Source: https://tanstack.com/query/latest/docs/framework/vue/reactivity.md Changing the userId ref in this example will not cause the query to re-fetch because the userId.value was extracted before being passed to the composable. ```ts // Reactive user ID ref. const userId = ref('1') // Fetches the user 1's projects. const { data: projects } = useUserProjects(userId.value) const onChangeUser = (newUserId: string) => { // Edits the userId, but the query will not re-fetch. userId.value = newUserId } ``` -------------------------------- ### Correct QueryClient Instantiation Patterns Source: https://tanstack.com/query/latest/docs/eslint/stable-query-client.md Use useState for lazy initialization, module-level constants, or local instantiation within async server components to ensure stability. ```tsx function App() { const [queryClient] = useState(() => new QueryClient()) return ( ) } ``` ```tsx const queryClient = new QueryClient() function App() { return ( ) } ``` ```tsx async function App() { const queryClient = new QueryClient() await queryClient.prefetchQuery(options) } ``` -------------------------------- ### Nuxt 3 Package Lock File Source: https://tanstack.com/query/latest/docs/framework/vue/examples/nuxt3 Ensures consistent dependency installations across different environments by locking the exact versions and sub-dependencies of all packages. ```json { "name": "@tanstack/query-example-vue-nuxt3", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@tanstack/query-example-vue-nuxt3", "dependencies": { "@tanstack/vue-query": "^5.90.2" }, "devDependencies": { "nuxt": "^3.12.4" } }, "node_modules/@babel/code-frame": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", "dev": true, "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/compat-data": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/core": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", "dev": true, "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", "@babel/helper-compilation-targets": "^7.29.7", "@babel/helper-module-transforms": "^7.29.7", "@babel/helpers": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" }, "engines": { "node": ">=6.9.0" }, "funding": { "type": "opencollective", "url": ``` -------------------------------- ### Build Nuxt 3 Application for Production Source: https://tanstack.com/query/latest/docs/framework/vue/examples/nuxt3 Compiles and optimizes the Nuxt 3 application for production deployment, generating static assets and server-side code. ```bash pnpm build ``` -------------------------------- ### Incorrect useMutation() property order Source: https://tanstack.com/query/latest/docs/eslint/mutation-property-order.md Example showing incorrect property ordering where onSettled appears before onMutate and onError, violating type inference requirements. ```tsx /* eslint "@tanstack/query/mutation-property-order": "warn" */ import { useMutation } from '@tanstack/react-query' const mutation = useMutation({ mutationFn: () => Promise.resolve('success'), onSettled: () => { results.push('onSettled-promise') return Promise.resolve('also-ignored') // Promise (should be ignored) }, onMutate: async () => { results.push('onMutate-async') await sleep(1) return { backup: 'async-data' } }, onError: async () => { results.push('onError-async-start') await sleep(1) results.push('onError-async-end') }, }) ``` -------------------------------- ### Enable Vue Query Devtools Plugin Source: https://tanstack.com/query/latest/docs/framework/vue/devtools.md Enable the Vue Query devtools plugin by setting `enableDevtoolsV6Plugin` to `true` in the `VueQueryPlugin` options during application setup. ```ts app.use(VueQueryPlugin, { enableDevtoolsV6Plugin: true, }) ``` -------------------------------- ### queryClient.ensureQueryData Source: https://tanstack.com/query/latest/docs/reference/QueryClient.md `ensureQueryData` is an asynchronous function that can be used to get an existing query's cached data. If the query does not exist, `queryClient.fetchQuery` will be called and its results returned. ```APIDOC ## queryClient.ensureQueryData ### Description `ensureQueryData` is an asynchronous function that can be used to get an existing query's cached data. If the query does not exist, `queryClient.fetchQuery` will be called and its results returned. ### Parameters - **options** (object) - Required - An object containing query options. - **queryKey** (QueryKey) - Required - The unique key for the query. - **queryFn** (Function) - Required - The function that fetches the data if the query does not exist. - **revalidateIfStale** (boolean) - Optional - Defaults to `false`. If set to `true`, stale data will be refetched in the background, but cached data will be returned immediately. - **...otherFetchQueryOptions** (object) - Optional - All other options supported by `queryClient.fetchQuery`. ### Returns - `Promise` - A promise that resolves with the query's data. ``` -------------------------------- ### Initialize TanStack Query in a React Application Source: https://tanstack.com/query/latest/docs/framework/react/examples/simple This snippet shows the basic structure for setting up TanStack Query in a React application, including imports, `QueryClient` initialization, and wrapping the root component with `QueryClientProvider` and `ReactQueryDevtools`. ```typescript import React from 'react' import ReactDOM from 'react-dom/client' import { QueryClient, QueryClientProvider, useQuery, } from '@tanstack/react-query' import { ReactQueryDevtools } from '@tanstack/react-query-devtools' const queryClient = new QueryClient() export default function App() { return ( ) } ``` -------------------------------- ### Correct useQuery with queryOptions Source: https://tanstack.com/query/latest/docs/eslint/prefer-query-options.md Wrap queryKey and queryFn in queryOptions to co-locate them, then pass the result to useQuery. This allows safe reuse and optional overrides like select. ```tsx /* eslint "@tanstack/query/prefer-query-options": "error" */ function getFooOptions(id) { return queryOptions({ queryKey: ['get', id], queryFn: () => Api.get(`/foo/${id}`), }) } function Component({ id }) { const query = useQuery(getFooOptions(id)) // ... } ``` ```tsx /* eslint "@tanstack/query/prefer-query-options": "error" */ function getFooOptions(id) { return queryOptions({ queryKey: ['get', id], queryFn: () => Api.get(`/foo/${id}`), }) } function useFooQuery(id) { return useQuery({ ...getFooOptions(id), select: (data) => data.foo }) } ``` -------------------------------- ### Get Query State with queryClient.getQueryState (TypeScript/TSX) Source: https://tanstack.com/query/latest/docs/reference/QueryClient.md Use this synchronous function to retrieve the current state of an existing query. It returns undefined if the query does not exist in the cache. ```tsx const state = queryClient.getQueryState(queryKey) console.log(state.dataUpdatedAt) ``` -------------------------------- ### queryClient.ensureInfiniteQueryData Source: https://tanstack.com/query/latest/docs/reference/QueryClient.md `ensureInfiniteQueryData` is an asynchronous function that can be used to get an existing infinite query's cached data. If the query does not exist, `queryClient.fetchInfiniteQuery` will be called and its results returned. ```APIDOC ## queryClient.ensureInfiniteQueryData ### Description `ensureInfiniteQueryData` is an asynchronous function that can be used to get an existing infinite query's cached data. If the query does not exist, `queryClient.fetchInfiniteQuery` will be called and its results returned. ### Parameters - **options** (object) - Required - An object containing infinite query options. - **queryKey** (QueryKey) - Required - The unique key for the infinite query. - **queryFn** (Function) - Required - The function that fetches the infinite data if the query does not exist. - **initialPageParam** (any) - Optional - The initial page parameter for infinite queries. - **getNextPageParam** (Function) - Optional - A function to determine the next page parameter for infinite queries. - **revalidateIfStale** (boolean) - Optional - Defaults to `false`. If set to `true`, stale data will be refetched in the background, but cached data will be returned immediately. - **...otherFetchInfiniteQueryOptions** (object) - Optional - All other options supported by `queryClient.fetchInfiniteQuery`. ### Returns - `Promise>` - A promise that resolves with the infinite query's data. ``` -------------------------------- ### Inferring Data Type with useQuery and Select Function Source: https://tanstack.com/query/latest/docs/framework/react/typescript.md This example shows how `useQuery` infers the data type after a `select` transformation, changing the original number type to a string. ```tsx const { data } = useQuery({ // ^? const data: string | undefined queryKey: ['test'], queryFn: () => Promise.resolve(5), select: (data) => data.toString(), }) ``` -------------------------------- ### Nuxt 3 Project Package Configuration Source: https://tanstack.com/query/latest/docs/framework/vue/examples/nuxt3 Specifies project metadata, defines scripts for development and building, and lists both runtime and development dependencies. ```json { "name": "@tanstack/query-example-vue-nuxt3", "private": true, "scripts": { "dev": "nuxi dev", "_build": "nuxi build", "_start": "node .output/server/index.mjs" }, "dependencies": { "@tanstack/vue-query": "^5.90.2" }, "devDependencies": { "nuxt": "^3.12.4" } } ``` -------------------------------- ### Invalidate Queries on Mutation Success in Vue Source: https://tanstack.com/query/latest/docs/framework/vue/guides/invalidations-from-mutations.md Utilize `onSuccess` with `queryClient.invalidateQueries` to refetch related data after a mutation in a Vue application. This example invalidates multiple query keys. ```tsx import { useMutation, useQueryClient } from '@tanstack/vue-query' const queryClient = useQueryClient() // When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key const mutation = useMutation({ mutationFn: addTodo, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['todos'] }) queryClient.invalidateQueries({ queryKey: ['reminders'] }) } }) ``` -------------------------------- ### Displaying Global Background Fetching State (Vue) Source: https://tanstack.com/query/latest/docs/framework/vue/guides/background-fetching-indicators.md Utilize the `useIsFetching` hook to show a global loading indicator when any query is actively fetching, including background refetches. ```vue ``` -------------------------------- ### Invalidate Queries on Mutation Success in React Source: https://tanstack.com/query/latest/docs/framework/vue/guides/invalidations-from-mutations.md Use `onSuccess` with `queryClient.invalidateQueries` to refetch related data after a mutation. This example shows invalidating single and multiple query keys. ```tsx import { useMutation, useQueryClient } from '@tanstack/react-query' const queryClient = useQueryClient() // When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key const mutation = useMutation({ mutationFn: addTodo, onSuccess: async () => { // If you're invalidating a single query await queryClient.invalidateQueries({ queryKey: ['todos'] }) // If you're invalidating multiple queries await Promise.all([ queryClient.invalidateQueries({ queryKey: ['todos'] }), queryClient.invalidateQueries({ queryKey: ['reminders'] }) ]) } }) ``` -------------------------------- ### Customizing Devtools Panel Height with Style Source: https://tanstack.com/query/latest/docs/framework/react/devtools.md Apply custom CSS styles to the devtools panel using the `style` prop. This example sets the panel height to 100%. ```typescript { height: '100%' } ``` -------------------------------- ### Implementing Infinite Query with Vue.js `useInfiniteQuery` Source: https://tanstack.com/query/latest/docs/framework/vue/guides/infinite-queries.md This Vue component demonstrates fetching and displaying paginated project data using `useInfiniteQuery`. It configures the `queryFn` for data retrieval and `getNextPageParam` to manage the cursor for loading more items. ```vue ``` -------------------------------- ### queryClient.getDefaultOptions() Source: https://tanstack.com/query/latest/docs/reference/QueryClient.md The getDefaultOptions method returns the default options which have been set when creating the client or with setDefaultOptions. ```APIDOC ## queryClient.getDefaultOptions() ### Description The getDefaultOptions method returns the default options which have been set when creating the client or with setDefaultOptions. ### Method getDefaultOptions ### Returns The default options. ### Code Example ```tsx const defaultOptions = queryClient.getDefaultOptions() ``` ``` -------------------------------- ### Configure VueQueryPlugin with an existing QueryClient instance Source: https://tanstack.com/query/latest/docs/framework/vue/guides/custom-client.md Provide a pre-instantiated `QueryClient` instance directly to `VueQueryPlugin` options for advanced control or integration with external libraries. ```tsx const myClient = new QueryClient(queryClientConfig) const vueQueryPluginOptions: VueQueryPluginOptions = { queryClient: myClient, } app.use(VueQueryPlugin, vueQueryPluginOptions) ``` -------------------------------- ### Prefetching a Query with Default `queryFn` using `queryClient.prefetchQuery` (TypeScript/TSX) Source: https://tanstack.com/query/latest/docs/reference/QueryClient.md This snippet shows how to prefetch a query when a default `queryFn` is configured, requiring only the `queryKey`. ```tsx await queryClient.prefetchQuery({ queryKey }) ``` -------------------------------- ### Get Multiple Queries Data with queryClient.getQueriesData Source: https://tanstack.com/query/latest/docs/reference/QueryClient.md This synchronous function retrieves cached data for multiple queries that match the provided `QueryFilters`, returning an empty array if no matches are found. ```tsx const data = queryClient.getQueriesData(filters) ```