================
CODE SNIPPETS
================
TITLE: Fetch Asynchronous Data using useQuery Hook in Vue Components
DESCRIPTION: Illustrates the basic usage of the `useQuery` hook within a Vue component's `setup` function. This hook is used to define and manage a data query, specifying a `queryKey` for caching and a `queryFn` for data fetching.
SOURCE: https://github.com/tanstack/query/blob/main/packages/vue-query/README.md#_snippet_2
LANGUAGE: tsx
CODE:
```
import { defineComponent } from 'vue'
import { useQuery } from '@tanstack/vue-query'
export default defineComponent({
name: 'MyComponent',
setup() {
const query = useQuery({ queryKey: ['todos'], queryFn: getTodos })
return {
query,
}
},
})
```
--------------------------------
TITLE: Fetch Data with useQuery in Vue Composition API using
...
```
--------------------------------
TITLE: Implement Asynchronous Setup with Vue Query's Suspense Mode
DESCRIPTION: This snippet illustrates how to define an asynchronous `setup` function within a Vue component to integrate with Vue Query's suspense mode. It uses `useQuery` to fetch data and then awaits the `suspense()` function, which is provided by `vue-query`, to ensure data is resolved before the component renders, enabling a 'fetch-on-render' pattern.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/suspense.md#_snippet_1
LANGUAGE: vue
CODE:
```
```
--------------------------------
TITLE: Initialize Vue Query Plugin in a Vue 3 Application
DESCRIPTION: Demonstrates how to integrate Vue Query into a Vue 3 application. It involves importing `createApp` and `VueQueryPlugin`, then registering the plugin with the Vue application instance using `app.use()`.
SOURCE: https://github.com/tanstack/query/blob/main/packages/vue-query/README.md#_snippet_1
LANGUAGE: tsx
CODE:
```
import { createApp } from 'vue'
import { VueQueryPlugin } from '@tanstack/vue-query'
import App from './App.vue'
createApp(App).use(VueQueryPlugin).mount('#app')
```
--------------------------------
TITLE: Basic Data Fetching and Mutation with TanStack Vue Query
DESCRIPTION: This Vue component demonstrates how to use `useQuery` to fetch a list of todos and `useMutation` to add a new todo. It also shows how to invalidate the query cache after a successful mutation to refetch the updated data, ensuring the UI reflects the latest state. The example includes basic loading, error, and success state handling.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/quick-start.md#_snippet_0
LANGUAGE: Vue
CODE:
```
Loading...Error: {{ error.message }}
{{ todo.title }}
```
--------------------------------
TITLE: Initialize TanStack Vue Query Plugin in Vue Application
DESCRIPTION: Demonstrates how to import and use the `VueQueryPlugin` to initialize TanStack Vue Query within a Vue application. This step is crucial before any query operations can be performed.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/installation.md#_snippet_1
LANGUAGE: tsx
CODE:
```
import { VueQueryPlugin } from '@tanstack/vue-query'
app.use(VueQueryPlugin)
```
--------------------------------
TITLE: Define component props in Vue 3 `
```
--------------------------------
TITLE: Pass Reactive Variables to Vue Query Options for Dynamic Behavior
DESCRIPTION: Explains how to make query options dynamic by passing reactive variables (e.g., `ref`) to `queryKey` and `enabled`. This allows the query to automatically re-evaluate or re-fetch data when the reactive variables change.
SOURCE: https://github.com/tanstack/query/blob/main/packages/vue-query/README.md#_snippet_3
LANGUAGE: tsx
CODE:
```
const id = ref(1)
const enabled = ref(false)
const query = useQuery({
queryKey: ['todos', id],
queryFn: () => getTodos(id),
enabled,
})
```
--------------------------------
TITLE: Install Vue Query Package with npm, pnpm, yarn, or bun
DESCRIPTION: Provides commands to install the `@tanstack/vue-query` package using various JavaScript package managers. Users of Vue 2.6 should also set up `@vue/composition-api`.
SOURCE: https://github.com/tanstack/query/blob/main/packages/vue-query/README.md#_snippet_0
LANGUAGE: bash
CODE:
```
npm i @tanstack/vue-query
```
LANGUAGE: bash
CODE:
```
pnpm add @tanstack/vue-query
```
LANGUAGE: bash
CODE:
```
yarn add @tanstack/vue-query
```
LANGUAGE: bash
CODE:
```
bun add @tanstack/vue-query
```
--------------------------------
TITLE: Initialize a basic query with injectQuery in Angular
DESCRIPTION: Demonstrates how to import and use `injectQuery` within an Angular component to fetch a list of todos. This snippet shows the basic setup for defining a query key and function for data retrieval.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/angular/guides/queries.md#_snippet_0
LANGUAGE: TypeScript
CODE:
```
import { injectQuery } from '@tanstack/angular-query-experimental'
export class TodosComponent {
info = injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodoList }))
}
```
--------------------------------
TITLE: Initialize TanStack Query with Vite SSR for State Hydration
DESCRIPTION: This JavaScript code demonstrates how to set up TanStack Query within a `vite-ssr` application's `main.js` entry point. It shows how to create a new `QueryClient` for each request, dehydrate the client state during SSR, and hydrate it on the client-side to ensure state synchronization between server and browser. This setup is crucial for seamless server-side rendering with TanStack Query.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/ssr.md#_snippet_5
LANGUAGE: javascript
CODE:
```
// main.js (entry point)
import App from './App.vue'
import viteSSR from 'vite-ssr/vue'
import {
QueryClient,
VueQueryPlugin,
hydrate,
dehydrate,
} from '@tanstack/vue-query'
export default viteSSR(App, { routes: [] }, ({ app, initialState }) => {
// -- This is Vite SSR main hook, which is called once per request
// Create a fresh VueQuery client
const queryClient = new QueryClient()
// Sync initialState with the client state
if (import.meta.env.SSR) {
// Indicate how to access and serialize VueQuery state during SSR
initialState.vueQueryState = { toJSON: () => dehydrate(queryClient) }
} else {
// Reuse the existing state in the browser
hydrate(queryClient, initialState.vueQueryState)
}
// Mount and provide the client to the app components
app.use(VueQueryPlugin, { queryClient })
})
```
--------------------------------
TITLE: Enable Official Vue Devtools Integration for Vue Query
DESCRIPTION: Code snippet to enable seamless integration with the official Vue devtools by setting `enableDevtoolsV6Plugin: true` in the `VueQueryPlugin` options. This integration adds custom inspector and timeline events specific to Vue Query, and the devtool code is treeshaken from production bundles by default.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/devtools.md#_snippet_2
LANGUAGE: typescript
CODE:
```
app.use(VueQueryPlugin, {
enableDevtoolsV6Plugin: true,
})
```
--------------------------------
TITLE: Type Inference for Basic TanStack Vue Query Data
DESCRIPTION: This example demonstrates how TanStack Vue Query automatically infers the type of the 'data' property from the 'queryFn's return value. Here, 'Promise.resolve(5)' leads to 'data' being inferred as 'Ref | Ref'.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/typescript.md#_snippet_0
LANGUAGE: tsx
CODE:
```
const { data } = useQuery({
// ^? const data: Ref | Ref
queryKey: ['test'],
queryFn: () => Promise.resolve(5),
})
```
--------------------------------
TITLE: Implement Paginated Queries with TanStack Vue Query
DESCRIPTION: This snippet demonstrates how to fetch paginated data using `useQuery` from TanStack Vue Query. It defines a `fetcher` function to retrieve posts based on a page number, manages the current page state with a `ref`, and uses `keepPreviousData` to prevent flickering when navigating between pages. Navigation buttons are provided to increment or decrement the page number.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/paginated-queries.md#_snippet_0
LANGUAGE: vue
CODE:
```
```
--------------------------------
TITLE: Implement Infinite Queries with TanStack Vue Query
DESCRIPTION: This example demonstrates how to use `useInfiniteQuery` from TanStack Vue Query to fetch and display paginated data. It defines a `fetchProjects` function to retrieve data with a cursor, then uses `useInfiniteQuery` to manage the data, loading states, and provide methods like `fetchNextPage` to load more data. The template renders the fetched projects and a 'Load More' button, handling various loading and error states.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/infinite-queries.md#_snippet_0
LANGUAGE: Vue
CODE:
```
Loading...Error: {{ error.message }}
Fetching...
{{ project.name }}
```
--------------------------------
TITLE: Configure specific query retries with useQuery in Vue Query
DESCRIPTION: This example shows how to set a specific number of retries for a single query using the `retry` option within `useQuery`. When a query fails, it will attempt to refetch up to the specified number of times before reporting an error.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/query-retries.md#_snippet_0
LANGUAGE: tsx
CODE:
```
import { useQuery } from '@tanstack/vue-query'
// Make a specific query retry a certain number of times
const result = useQuery({
queryKey: ['todos', 1],
queryFn: fetchTodoListPage,
retry: 10, // Will retry failed requests 10 times before displaying an error
})
```
--------------------------------
TITLE: Configure TanStack Vue Query Plugin for Nuxt 3 SSR
DESCRIPTION: Initializes the `QueryClient` for TanStack Vue Query within a Nuxt 3 plugin. This setup handles server-side dehydration of query states and client-side hydration, ensuring state transfer for SSR.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/ssr.md#_snippet_0
LANGUAGE: TypeScript
CODE:
```
import type {
DehydratedState,
VueQueryPluginOptions,
} from '@tanstack/vue-query'
import {
VueQueryPlugin,
QueryClient,
hydrate,
dehydrate,
} from '@tanstack/vue-query'
// Nuxt 3 app aliases
import { defineNuxtPlugin, useState } from '#imports'
export default defineNuxtPlugin((nuxt) => {
const vueQueryState = useState('vue-query')
// Modify your Vue Query global settings here
const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 5000 } },
})
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) {
hydrate(queryClient, vueQueryState.value)
}
})
```
--------------------------------
TITLE: Handling Query States and Displaying Data in Vue.js Components
DESCRIPTION: Illustrates how to manage and display different states of an asynchronous query (pending, error, success) within a Vue.js component using `@tanstack/vue-query`. It provides two common patterns for accessing and reacting to query status changes in the template, allowing for dynamic UI updates based on the data's loading state.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/queries.md#_snippet_1
LANGUAGE: vue
CODE:
```
Loading...Error: {{ error.message }}
```
--------------------------------
TITLE: Basic Data Fetching with useQuery in Vue.js (TypeScript)
DESCRIPTION: Demonstrates the fundamental usage of `useQuery` from `@tanstack/vue-query` to fetch data. This example shows how to define a `queryKey` for caching and a `queryFn` to execute the asynchronous data fetching logic, returning the query result.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/queries.md#_snippet_0
LANGUAGE: ts
CODE:
```
import { useQuery } from '@tanstack/vue-query'
const result = useQuery({ queryKey: ['todos'], queryFn: fetchTodoList })
```
--------------------------------
TITLE: Configure a default query function for TanStack Query in Vue
DESCRIPTION: This snippet defines a `defaultQueryFn` that uses `axios` to fetch data from `jsonplaceholder.typicode.com` based on the `queryKey`. It then shows how to apply this default function globally by configuring `VueQueryPluginOptions` and passing it to `app.use(VueQueryPlugin)`, simplifying subsequent `useQuery` calls to only require a key.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/default-query-function.md#_snippet_0
LANGUAGE: TypeScript
CODE:
```
// 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 vueQueryPluginOptions: VueQueryPluginOptions = {
queryClientConfig: {
defaultOptions: { queries: { queryFn: defaultQueryFn } },
},
}
app.use(VueQueryPlugin, vueQueryPluginOptions)
// All you have to do now is pass a key!
const { status, data, error, isFetching } = useQuery({
queryKey: [`/posts/${postId}`],
})
```
--------------------------------
TITLE: Configure Vue Query Plugin with QueryClientConfig (TypeScript)
DESCRIPTION: This example shows how to initialize the `VueQueryPlugin` by passing a `QueryClientConfig` object. The plugin will internally create a `QueryClient` instance based on this configuration, allowing you to set default options like `staleTime` for all queries.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/custom-client.md#_snippet_0
LANGUAGE: tsx
CODE:
```
const vueQueryPluginOptions: VueQueryPluginOptions = {
queryClientConfig: {
defaultOptions: { queries: { staleTime: 3600 } },
},
}
app.use(VueQueryPlugin, vueQueryPluginOptions)
```
--------------------------------
TITLE: Conditionally enable TanStack Query with reactive `enabled` option (Vue)
DESCRIPTION: Demonstrates how to use reactive values within the `enabled` option of `useQuery` in TanStack Query. This allows for conditional data fetching based on dynamic reactive state, such as enabling the query only when `userId.value` matches `activeUserId.value`.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/reactivity.md#_snippet_11
LANGUAGE: typescript
CODE:
```
export function useUserProjects(userId: MaybeRef) {
return useQuery(
queryKey: ['userProjects', userId],
queryFn: () => api.fetchUserProjects(toValue(userId)),
enabled: () => userId.value === activeUserId.value,
);
}
```
--------------------------------
TITLE: Configure TanStack Vue Query Plugin for Nuxt 2 SSR
DESCRIPTION: Sets up the `QueryClient` for TanStack Vue Query in a Nuxt 2 plugin. It manages storing the `queryClient` in `ssrContext` on the server and hydrating the client-side `QueryClient` with server-provided state.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/ssr.md#_snippet_2
LANGUAGE: JavaScript
CODE:
```
import Vue from 'vue'
import { VueQueryPlugin, QueryClient, hydrate } from '@tanstack/vue-query'
export default (context) => {
// Modify your Vue Query global settings here
const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 5000 } },
})
if (process.server) {
context.ssrContext.VueQuery = queryClient
}
if (process.client) {
Vue.use(VueQueryPlugin, { queryClient })
if (context.nuxtState && context.nuxtState.vueQueryState) {
hydrate(queryClient, context.nuxtState.vueQueryState)
}
}
}
```
--------------------------------
TITLE: Make props reactive with `computed` for TanStack Query (Vue)
DESCRIPTION: Shows how to ensure a component prop is reactive when used in a TanStack Query by wrapping it with Vue's `computed` function. This method creates a reactive `userId` that allows the `useUserProjects` query to react to changes in `props.userId`.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/reactivity.md#_snippet_8
LANGUAGE: typescript
CODE:
```
const userId = computed(() => props.userId)
// Reacts to changes in props.userId.
const { data: projects } = useUserProjects(userId)
```
--------------------------------
TITLE: Perform Data Mutations with Vue 3 Composition API
DESCRIPTION: This example demonstrates how to define and execute a data mutation using `useMutation` within a Vue 3 component's `
Adding todo...An error occurred: {{ error.message }}Todo added!
```
--------------------------------
TITLE: Perform Server-Side Data Fetching in Vue Components with TanStack Query
DESCRIPTION: This Vue component example illustrates how to use `onServerPrefetch` with TanStack Query to prefetch data on the server. By calling `suspense` within `onServerPrefetch`, the component ensures that the query data is fetched and available before the server renders the initial HTML. This approach optimizes initial page load performance and enables dynamic content to be rendered on the server.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/ssr.md#_snippet_6
LANGUAGE: html
CODE:
```
{{ data }}
```
--------------------------------
TITLE: Configure Vue Query Plugin with existing QueryClient (TypeScript)
DESCRIPTION: This snippet demonstrates how to provide an already instantiated `QueryClient` object to the `VueQueryPlugin`. This approach is useful when the `QueryClient` needs to be created and managed outside of the Vue context, for instance, when integrating with other libraries.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/custom-client.md#_snippet_1
LANGUAGE: tsx
CODE:
```
const myClient = new QueryClient(queryClientConfig)
const vueQueryPluginOptions: VueQueryPluginOptions = {
queryClient: myClient,
}
app.use(VueQueryPlugin, vueQueryPluginOptions)
```
--------------------------------
TITLE: Register Vue Query Plugin in Nuxt 2 Configuration
DESCRIPTION: Illustrates how to add the `vue-query.js` plugin to the `plugins` array in `nuxt.config.js` for a Nuxt 2 application, enabling its functionality.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/ssr.md#_snippet_3
LANGUAGE: JavaScript
CODE:
```
module.exports = {
...
plugins: ['~/plugins/vue-query.js'],
}
```
--------------------------------
TITLE: Integrate TanStack Vue Query Devtools Component in Vue 3
DESCRIPTION: Example demonstrating how to import and use the `VueQueryDevtools` component within a Vue 3 application's template. This component provides a fixed, floating devtools panel with a toggle, and its state is remembered in localStorage across reloads. It should be placed as high as possible in the Vue app's component tree for optimal functionality.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/devtools.md#_snippet_1
LANGUAGE: vue
CODE:
```
The app!
```
--------------------------------
TITLE: Use Solid Query's `suspense` Function for Data Fetching
DESCRIPTION: This snippet illustrates how to use the `suspense` function provided by `solid-query` within a component's `setup` function. It fetches data using `useQuery` and then explicitly calls `await suspense()` to ensure the query data is resolved before the component renders, enabling a fetch-on-render pattern.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/solid/guides/suspense.md#_snippet_1
LANGUAGE: vue
CODE:
```
```
--------------------------------
TITLE: Install TanStack Vue Query Devtools Package
DESCRIPTION: Instructions for installing the `@tanstack/vue-query-devtools` package using various package managers (npm, pnpm, yarn, bun). This package provides a component for integrating devtools directly into a Vue application, and is only included in development builds by default.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/devtools.md#_snippet_0
LANGUAGE: bash
CODE:
```
npm i @tanstack/vue-query-devtools
```
LANGUAGE: bash
CODE:
```
pnpm add @tanstack/vue-query-devtools
```
LANGUAGE: bash
CODE:
```
yarn add @tanstack/vue-query-devtools
```
LANGUAGE: bash
CODE:
```
bun add @tanstack/vue-query-devtools
```
--------------------------------
TITLE: Use reactive getters for props in TanStack Query (Vue)
DESCRIPTION: Presents the recommended approach for using a component prop reactively within a TanStack Query without an intermediate `computed` property. By passing a reactive getter function (`() => props.userId`), the query reacts to changes in `props.userId` with minimal overhead and no unnecessary memoization.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/reactivity.md#_snippet_10
LANGUAGE: typescript
CODE:
```
// Reacts to changes in props.userId. No `computed` needed!
const { data: projects } = useUserProjects(() => props.userId)
```
--------------------------------
TITLE: Install TanStack Vue Query via Package Managers
DESCRIPTION: Instructions for installing the TanStack Vue Query library using different Node.js package managers: npm, pnpm, yarn, and bun. This is the first step to integrate the library into a Vue.js project.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/installation.md#_snippet_0
LANGUAGE: bash
CODE:
```
npm i @tanstack/vue-query
```
LANGUAGE: bash
CODE:
```
pnpm add @tanstack/vue-query
```
LANGUAGE: bash
CODE:
```
yarn add @tanstack/vue-query
```
LANGUAGE: bash
CODE:
```
bun add @tanstack/vue-query
```
--------------------------------
TITLE: Incorrect direct prop usage in TanStack Query (Vue)
DESCRIPTION: Demonstrates an anti-pattern where a component prop is used directly within a `useUserProjects` query. This approach is problematic because direct property access on reactive variables causes reactivity to be lost, preventing the query from reacting to `props.userId` changes.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/reactivity.md#_snippet_7
LANGUAGE: typescript
CODE:
```
// Won't react to changes in props.userId.
const { data: projects } = useUserProjects(props.userId)
```
--------------------------------
TITLE: Disable Window Focus Refetching Globally in Vue Query
DESCRIPTION: This code snippet demonstrates how to globally disable the `refetchOnWindowFocus` option for all queries within a Vue.js application using TanStack Vue Query. By setting `refetchOnWindowFocus: false` in the `defaultOptions` of the `queryClientConfig`, data will not automatically refetch when the browser window regains focus.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/window-focus-refetching.md#_snippet_0
LANGUAGE: javascript
CODE:
```
const vueQueryPluginOptions: VueQueryPluginOptions = {
queryClientConfig: {
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
},
},
},
}
app.use(VueQueryPlugin, vueQueryPluginOptions)
```
--------------------------------
TITLE: Type Inference for Custom Data Structures in TanStack Vue Query
DESCRIPTION: This example shows type inference when 'queryFn' returns a Promise of a custom type, such as an array of 'Group' objects. TanStack Vue Query correctly infers 'data' as 'Ref | Ref', ensuring type safety for complex data.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/typescript.md#_snippet_2
LANGUAGE: tsx
CODE:
```
const fetchGroups = (): Promise =>
axios.get('/groups').then((response) => response.data)
const { data } = useQuery({ queryKey: ['groups'], queryFn: fetchGroups })
// ^? const data: Ref | Ref
```
--------------------------------
TITLE: Displaying data and loading states with useQuery in Vue
DESCRIPTION: This snippet demonstrates how to use the `useQuery` hook from `@tanstack/vue-query` to fetch data and display different UI states based on the query's status. It shows indicators for initial loading (`isPending`), background refreshing (`isFetching`), and error states (`isError`), finally rendering the data when successful.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/background-fetching-indicators.md#_snippet_0
LANGUAGE: vue
CODE:
```
Refreshing...
Loading...Error: {{ error.message }}
{{ todo.title }}
```
--------------------------------
TITLE: Prefetch and Dehydrate Queries in Nuxt 2 Vue Component
DESCRIPTION: Shows how to prefetch data using `onServerPrefetch` and `suspense` in a Nuxt 2 Vue component. It also demonstrates accessing the `queryClient` from the SSR context and dehydrating its state for client-side hydration, allowing selective prefetching.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/ssr.md#_snippet_4
LANGUAGE: Vue
CODE:
```
{{ data }}
```
--------------------------------
TITLE: Configure global retry delay strategy in Vue Query
DESCRIPTION: This example demonstrates how to set a global retry delay strategy for all queries using the `retryDelay` option within the `queryClientConfig` of `VueQueryPlugin`. The `retryDelay` function calculates an exponential backoff, ensuring increasing delays between retry attempts.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/query-retries.md#_snippet_1
LANGUAGE: ts
CODE:
```
import { VueQueryPlugin } from '@tanstack/vue-query'
const vueQueryPluginOptions = {
queryClientConfig: {
defaultOptions: {
queries: {
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
},
},
},
}
app.use(VueQueryPlugin, vueQueryPluginOptions)
```
--------------------------------
TITLE: Handling and Narrowing Error Types in TanStack Vue Query
DESCRIPTION: This snippet shows how the 'error' property from 'useQuery' is initially typed as 'Ref'. It then demonstrates how to narrow the error type using an 'instanceof' check, allowing specific error handling for 'Error' objects.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/typescript.md#_snippet_4
LANGUAGE: tsx
CODE:
```
const { error } = useQuery({ queryKey: ['groups'], queryFn: fetchGroups })
// ^? const error: Ref
if (error.value instanceof Error) {
error.value
// ^? const error: Error
}
```
--------------------------------
TITLE: Set up a React Query `useMutation` for optimistic UI updates
DESCRIPTION: This snippet demonstrates the basic setup of a `useMutation` hook in React Query for performing an asynchronous operation (e.g., adding a todo). It includes `mutationFn` for the API call and `onSettled` to invalidate queries, ensuring the UI reflects the latest data after the mutation completes, whether successful or not.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/react/guides/optimistic-updates.md#_snippet_0
LANGUAGE: tsx
CODE:
```
const addTodoMutation = useMutation({
mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
// make sure to _return_ the Promise from the query invalidation
// so that the mutation stays in `pending` state until the refetch is finished
onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
})
const { isPending, submittedAt, variables, mutate, isError } = addTodoMutation
```
--------------------------------
TITLE: Basic Paginated Query in TanStack Query
DESCRIPTION: This example demonstrates a basic paginated query using `useQuery` in TanStack Query, where the current page information is included in the `queryKey`. While functional, this approach can cause the UI to jump between success and pending states as each new page is treated as a distinct query, leading to a suboptimal user experience.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/react/guides/paginated-queries.md#_snippet_0
LANGUAGE: tsx
CODE:
```
const result = useQuery({
queryKey: ['projects', page],
queryFn: fetchProjects,
})
```
--------------------------------
TITLE: Type Narrowing for TanStack Vue Query Data
DESCRIPTION: This code demonstrates how TypeScript can narrow the type of 'data' based on the 'isSuccess' status. When 'isSuccess' is true, 'data' is guaranteed to have its resolved type (e.g., 'number'), removing the 'undefined' possibility and allowing direct access to its properties.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/typescript.md#_snippet_3
LANGUAGE: tsx
CODE:
```
const { data, isSuccess } = reactive(
useQuery({
queryKey: ['test'],
queryFn: () => Promise.resolve(5),
}),
)
if (isSuccess) {
data
// ^? const data: number
}
```
--------------------------------
TITLE: Registering a Default Error Type for TanStack Vue Query
DESCRIPTION: This example illustrates how to globally register a default error type for '@tanstack/vue-query' using module augmentation. By setting 'defaultError: unknown', developers are encouraged to explicitly narrow error types at call sites, promoting robust error handling.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/typescript.md#_snippet_5
LANGUAGE: tsx
CODE:
```
import '@tanstack/vue-query'
declare module '@tanstack/vue-query' {
interface Register {
// Use unknown so call sites must narrow explicitly.
defaultError: unknown
}
}
const { error } = useQuery({ queryKey: ['groups'], queryFn: fetchGroups })
// ^? const error: unknown | null
```
--------------------------------
TITLE: Configure basic initial data for a query
DESCRIPTION: Demonstrates setting `initialData` directly with a pre-fetched value. The query will use this data immediately upon initialization, but will also refetch if no `staleTime` is specified.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/angular/guides/initial-query-data.md#_snippet_0
LANGUAGE: typescript
CODE:
```
result = injectQuery(() => ({
queryKey: ['todos'],
queryFn: () => fetch('/todos'),
initialData: initialTodos,
}))
```
--------------------------------
TITLE: Basic useQuery Hook Usage in TanStack Query
DESCRIPTION: Demonstrates the fundamental usage of the `useQuery` hook from `@tanstack/react-query` to subscribe to an asynchronous data source. It shows how to define a query with a unique `queryKey` and a `queryFn` that fetches data.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/react/guides/queries.md#_snippet_0
LANGUAGE: tsx
CODE:
```
import { useQuery } from '@tanstack/react-query'
function App() {
const info = useQuery({ queryKey: ['todos'], queryFn: fetchTodoList })
}
```
--------------------------------
TITLE: Illustrate internal custom QueryClient key combination (TypeScript)
DESCRIPTION: This example visually explains how a custom `queryClientKey` is internally combined with the default key by Vue Query. It shows the resulting format (e.g., `VUE_QUERY_CLIENT:Foo`), clarifying the underlying mechanism without requiring direct user implementation.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/custom-client.md#_snippet_5
LANGUAGE: tsx
CODE:
```
const vueQueryPluginOptions: VueQueryPluginOptions = {
queryClientKey: 'Foo',
}
app.use(VueQueryPlugin, vueQueryPluginOptions) // -> VUE_QUERY_CLIENT:Foo
```
--------------------------------
TITLE: Type Inference with 'select' Option in TanStack Vue Query
DESCRIPTION: This snippet illustrates how the 'select' option influences type inference. When 'select' transforms the 'queryFn's result, the 'data' property's type is inferred based on the 'select' function's return type. In this case, 'data.toString()' results in 'Ref | Ref'.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/typescript.md#_snippet_1
LANGUAGE: tsx
CODE:
```
const { data } = useQuery({
// ^? const data: Ref | Ref
queryKey: ['test'],
queryFn: () => Promise.resolve(5),
select: (data) => data.toString(),
})
```
--------------------------------
TITLE: Global background fetching indicator with useIsFetching in Vue
DESCRIPTION: This snippet illustrates how to use the `useIsFetching` hook from `@tanstack/vue-query` to create a global indicator for any ongoing background fetches. This is useful for showing a general loading state when multiple queries might be refreshing in the background.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/background-fetching-indicators.md#_snippet_1
LANGUAGE: vue
CODE:
```
Queries are fetching in the background...
```
--------------------------------
TITLE: Wrap Component with Vue Suspense for Loading States
DESCRIPTION: This example demonstrates how to use Vue's built-in `Suspense` component to wrap a component that might suspend during rendering. It defines a default slot for the suspendable component and a fallback slot to display content (e.g., 'Loading...') while the component is awaiting data.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/suspense.md#_snippet_0
LANGUAGE: vue
CODE:
```
Loading...
```
--------------------------------
TITLE: Prefetch Data with `onServerPrefetch` in Nuxt 3
DESCRIPTION: Demonstrates prefetching data on the server using `onServerPrefetch` and `suspense` with `useQuery` in a Nuxt 3 component. This ensures initial query data is available before server-side rendering.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/ssr.md#_snippet_1
LANGUAGE: TypeScript
CODE:
```
export default defineComponent({
setup() {
const { data, suspense } = useQuery({
queryKey: ['test'],
queryFn: fetcher,
})
onServerPrefetch(async () => {
await suspense()
})
return { data }
},
})
```
--------------------------------
TITLE: Set static placeholder data for a query in TanStack Query
DESCRIPTION: This example demonstrates how to provide static placeholder data to a `useQuery` hook in TanStack Query. The `placeholderData` option is set to a pre-defined value, `placeholderTodos`, which will be used as initial data while the actual query is fetching. This is useful for immediately displaying some content to the user.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/placeholder-query-data.md#_snippet_0
LANGUAGE: tsx
CODE:
```
const result = useQuery({
queryKey: ['todos'],
queryFn: () => fetch('/todos'),
placeholderData: placeholderTodos,
})
```
--------------------------------
TITLE: Defining Basic Query Functions in TanStack Query
DESCRIPTION: Illustrates various valid configurations for defining the `queryFn` property within `useQuery` hooks. Examples include direct function references, inline arrow functions, async/await patterns, and destructuring `queryKey` from the context.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/react/guides/query-functions.md#_snippet_0
LANGUAGE: tsx
CODE:
```
useQuery({ queryKey: ['todos'], queryFn: fetchAllTodos })
useQuery({ queryKey: ['todos', todoId], queryFn: () => fetchTodoById(todoId) })
useQuery({
queryKey: ['todos', todoId],
queryFn: async () => {
const data = await fetchTodoById(todoId)
return data
},
})
useQuery({
queryKey: ['todos', todoId],
queryFn: ({ queryKey }) => fetchTodoById(queryKey[1]),
})
```
--------------------------------
TITLE: Prepopulating Query Cache with `initialData` in TanStack Query
DESCRIPTION: Demonstrates the basic usage of the `initialData` option in `useQuery` to provide initial data to the query cache. This allows the query to skip its initial loading state and display the provided data immediately. Note that `initialData` is persisted to the cache.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/react/guides/initial-query-data.md#_snippet_0
LANGUAGE: tsx
CODE:
```
const result = useQuery({
queryKey: ['todos'],
queryFn: () => fetch('/todos'),
initialData: initialTodos,
})
```
--------------------------------
TITLE: Basic `injectQuery` Function Definitions
DESCRIPTION: Illustrates fundamental ways to define `queryFn` within `injectQuery`, showcasing direct function calls, arrow functions, asynchronous operations, and basic `queryKey` access for simple data fetching.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/angular/guides/query-functions.md#_snippet_0
LANGUAGE: typescript
CODE:
```
injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchAllTodos }))
injectQuery(() => ({ queryKey: ['todos', todoId], queryFn: () => fetchTodoById(todoId) })
injectQuery(() => ({
queryKey: ['todos', todoId],
queryFn: async () => {
const data = await fetchTodoById(todoId)
return data
},
}))
injectQuery(() => ({
queryKey: ['todos', todoId],
queryFn: ({ queryKey }) => fetchTodoById(queryKey[1]),
}))
```
--------------------------------
TITLE: Fetch Multiple Dependent Queries with TanStack Query `useQueries` (TypeScript)
DESCRIPTION: This snippet illustrates fetching multiple dependent queries efficiently using TanStack Query's `useQueries` hook. It initially fetches a list of user IDs, then dynamically constructs an array of queries to retrieve messages for each user. This pattern is useful for parallelizing dependent fetches based on a primary query's result.
SOURCE: https://github.com/tanstack/query/blob/main/docs/framework/vue/guides/dependent-queries.md#_snippet_1
LANGUAGE: typescript
CODE:
```
// 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, // if userIds.value is undefined or has no items, an empty array will be returned
})
```