Vue Query 03 ⚡ useQuery Fundamentals — Query Keys, Query Functions, and Result Handling
The useQuery hook is the primary tool for fetching and managing server state in a Vue application. While the installation of the plugin provides the infrastructure, useQuery is the actual interface used within components to declare a data dependency. Unlike traditional imperative fetching where you write code to “go get the data,” useQuery is declarative: you describe what the data is (the Query Key) and how to get it (the Query Function), and the library manages the complexity of the request lifecycle, caching, and reactivity for you.
At its core, useQuery is a state machine. It transitions through a series of predictable statuses based on the success or failure of the network request and the state of the cache. For developers, this means no longer having to manually create ref(false) for loading states or ref(null) for error objects. The hook returns a reactive object containing everything needed to render a robust UI, including the data itself, various status flags, and utility functions for manual control. Understanding these fundamentals is the difference between a application that merely “works” and one that provides a seamless, professional user experience.
This chapter dives deep into the two mandatory pillars of a query: the Query Key and the Query Function. We will explore how keys act as the primary identifiers for the cache and how the query function must behave to ensure errors are handled correctly. We will also dissect the reactive result object, focusing on the nuanced differences between “pending,” “fetching,” and “error” states to help you build interfaces that never leave the user guessing.
Key point: Every useQuery instance requires a unique array-based Query Key for identification and an asynchronous Query Function that returns a Promise; the hook then provides reactive flags like isPending and isError to manage the UI state.
Why exists
The Cache Identification problem.
In a global cache, there must be a way to distinguish between “User #1” and “User #2.” Without a consistent naming convention, data would overwrite itself. Query Keys exist as a unique addressing system. Because they are arrays, they allow for hierarchical organization, ensuring that when data for a specific ID changes, it doesn’t affect other unrelated cached data.
The Automatic Dependency problem.
When a user changes a filter or a page number, the data needs to refresh. In standard Vue, you would have to watch a variable and manually call a fetch function. Query Keys solve this by acting as dependencies. If a reactive value is included in the Query Key array, Vue Query automatically triggers a refetch whenever that value changes, making synchronization automatic and declarative.
The State Machine complexity problem.
Handling every possible state of a network request is difficult. What if the data is in the cache but currently updating? What if the first request failed, but we are retrying? These edge cases result in complex “if/else” logic in components. The reactive flags like isPending and isFetching exist to provide a standardized state machine, allowing the UI to react to the granular details of the request lifecycle.
The Error Propagation problem.
The browser’s native fetch API is notoriously silent about HTTP errors like 404 or 500; it only throws if the network itself fails. This leads to apps that show “success” for empty data when a server error actually occurred. Query Functions in Vue Query exist to enforce a “Promise-based” contract: if the function throws or returns a rejected promise, the library officially recognizes an error state, triggering retries and updating the isError flag.
The Deduplication logic problem.
If two components on a page both request the same data, they shouldn’t trigger two network calls. Vue Query uses the Query Key to recognize these overlaps. By checking the key before executing the Query Function, the library can “deduplicate” the request, letting the second component wait for the first request’s result, saving bandwidth and server resources.
The UI Performance problem.
Showing a blank screen or a spinner every time a user navigates back to a page is jarring. The result handling logic in useQuery exists to support the “Stale-While-Revalidate” pattern. It allows the component to access the data from the cache immediately while the status flags indicate that a background update is happening, providing a much smoother and faster user experience.
a. The Query Key: Identification and Dependencies
The Query Key is the most important part of useQuery. It is an array of values that uniquely identifies the data in the cache. Vue Query serializes this array into a string internally to use as a lookup key. While you can use simple strings, arrays are the standard because they can contain dynamic information like IDs, categories, or sort orders.
// A simple, static key
const { data } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
// A hierarchical key with an ID
const { data: todo } = useQuery({
queryKey: ['todos', 5],
queryFn: () => fetchTodoById(5)
})
// A complex key with a filter object
const { data: list } = useQuery({
queryKey: ['todos', { status: 'done', page: 1 }],
queryFn: fetchFilteredTodos
})
The order of items in the array matters. ['todos', 5] is not the same as [5, 'todos']. However, objects inside the array are checked for “deep equality,” meaning ['todos', { a: 1, b: 2 }] is considered identical to ['todos', { b: 2, a: 1 }].
One of the most powerful features of Query Keys is their role as reactive dependencies. If you include a ref or a computed value in the key, Vue Query will watch that value. When it changes, the key changes, the cache lookup fails (because it’s a “new” key), and a refetch is automatically triggered.
<script setup>
const userId = ref(1)
const { data } = useQuery({
// When userId.value changes, this query re-runs!
queryKey: ['user', userId],
queryFn: () => fetchUser(userId.value)
})
</script>
b. The Query Function: Data Retrieval and Errors
The Query Function (queryFn) is an asynchronous function that must return a Promise. This function is where the actual network request (using fetch, axios, or any other library) takes place. The promise should either resolve with the data or throw an error.
A critical detail when using the native fetch API: it does not throw an error for status codes like 404 or 500. It only throws if there is a network failure or if the request is blocked. To make Vue Query’s error handling work correctly, you must manually check the response status and throw an error yourself.
const { data, error, isError } = useQuery({
queryKey: ['posts'],
queryFn: async () => {
const response = await fetch('/api/posts')
// Manual error check is REQUIRED for native fetch
if (!response.ok) {
throw new Error('Server responded with an error')
}
return response.json()
}
})
The Query Function receives a QueryFunctionContext object as an argument. This object contains the queryKey, which can be useful if you want to write a generic fetching function that extracts the ID directly from the key.
const fetchItem = async ({ queryKey }) => {
const [_key, id] = queryKey // Desctructure ['items', 5]
const res = await fetch(`/api/items/${id}`)
return res.json()
}
// In component
useQuery({ queryKey: ['items', 5], queryFn: fetchItem })
c. Handling Result States: Pending, Fetching, and Error
useQuery returns a reactive object that describes the current state of the query. In TanStack Query v5, the terminology changed slightly to be more precise. The three main flags you will use are isPending, isFetching, and isError.
isPending: This means the query has no data in the cache and is currently performing its initial fetch. This is when you usually show a full-page spinner or skeleton screens.isFetching: This is a more general flag. It is true whenever a request is in-flight, including background refetches. You might use this to show a small loading indicator in the corner of the UI while keeping the old data visible.isError: This becomes true if the query function throws an error. When this is true, theerrorobject becomes available, containing the details of the failure.
<template>
<!-- isPending: No data yet, first load -->
<div v-if="isPending">
<SkeletonLoader />
</div>
<!-- isError: Something went wrong -->
<div v-else-if="isError">
<p>Error: {{ error.message }}</p>
<button @click="refetch">Retry</button>
</div>
<!-- success: We have data -->
<div v-else>
<ul>
<li v-for="item in data" :key="item.id">{{ item.title }}</li>
</ul>
<!-- isFetching: Background update is happening -->
<small v-if="isFetching">Updating in background...</small>
</div>
</template>
The data property holds the result of the successful query. Because of the “Stale-While-Revalidate” logic, data might contain “old” information from the cache while isFetching is true. This is a feature, not a bug—it allows your UI to remain interactive and populated while the latest updates are retrieved.
Complete Example Session
// ============================================
// PART 1: THE IMPORTS
// ============================================
import { useQuery } from '@tanstack/vue-query'
import { ref, computed } from 'vue'
// ============================================
// PART 2: DYNAMIC STATE
// ============================================
const postId = ref(1)
// ============================================
// PART 3: THE QUERY DEFINITION
// ============================================
const {
data,
isPending,
isFetching,
isError,
error,
refetch
} = useQuery({
// PART 4: REACTIVE QUERY KEY
queryKey: ['post', postId],
// PART 5: THE QUERY FUNCTION
queryFn: async () => {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${postId.value}`)
if (!res.ok) throw new Error('Post not found')
return res.json()
},
// PART 6: CONFIGURATION (Optional)
retry: 2,
staleTime: 1000 * 30
})
// ============================================
// PART 7: LOGGING STATES
// ============================================
// console.log('Current Data:', data.value)
// console.log('Is Loading for the first time?', isPending.value)
// console.log('Is any network call happening?', isFetching.value)
// ============================================
// PART 8: TRIGGERING REFETCH
// ============================================
const manualRefresh = () => refetch()
// ============================================
// PART 9: UPDATING DEPENDENCIES
// ============================================
const nextPost = () => {
postId.value++ // This automatically triggers the query above
}
// ============================================
// PART 10: DERIVED STATE
// ============================================
const postTitle = computed(() => data.value?.title || 'No Title')
The parts above cover a standard implementation of useQuery, demonstrating how reactive keys, error-aware functions, and status flags work together to create a dynamic data-fetching system.
Quick Reference
The useQuery Result Object
| Property | Type | Description |
|---|---|---|
data | T | The actual data returned from the function |
isPending | Boolean | True if first fetch is active and no data exists |
isFetching | Boolean | True if any network request is active |
isError | Boolean | True if the last fetch failed |
error | Error | The error object thrown by the queryFn |
status | String | 'pending', 'error', or 'success' |
refetch | Function | Function to manually trigger a fetch |
Query Key Syntax
| Type | Example | Use Case |
|---|---|---|
| Simple | ['posts'] | Global list, no filters |
| Parametric | ['posts', 1] | Specific resource by ID |
| Filtered | ['posts', { sort: 'asc' }] | Lists with search/sort params |
| Nested | ['user', 1, 'comments'] | Child resources |
Status vs. FetchStatus (V5)
| status | fetchStatus | UI Meaning |
|---|---|---|
pending | fetching | Initial hard load (no data) |
success | fetching | Background refresh (has old data) |
success | idle | Idle state (has data, not fetching) |
error | idle | Failed state |
Best Practices
✅ Do This:
// Use an array for ALL query keys, even simple ones
queryKey: ['todos'] // ✅
// Throw errors in the query function so isError works
if (!res.ok) throw new Error(); // ✅
// Use isPending for the initial screen-wide loading state
if (isPending) return <BigSpinner /> // ✅
// Include all variables used in queryFn inside the queryKey
queryKey: ['user', userId] // ✅
❌ Don’t Do This:
// Don't use strings as query keys (they are converted to arrays)
queryKey: 'todos' // ❌
// Don't modify external state inside a queryFn (side effects)
queryFn: () => { myRef.value = 'done'; return fetch(); } // ❌
// Don't forget to handle the error state in the template
// (Users will just see an empty screen or old data) // ❌
// Don't use data.value without optional chaining or checks
console.log(data.value.name) // Crash if data is undefined // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| No Refetch on ID change | ID was not included in the queryKey | Add the ID variable to the queryKey array |
isError is never true | fetch doesn’t throw on 404/500 | Manually throw an error if !res.ok |
| Infinite Loop | queryFn updates a reactive value in the key | Remove state updates from the queryFn |
Data is undefined | Query hasn’t finished yet | Use isPending check or initialData |
| Stale Data in UI | Component doesn’t react to isFetching | Add a background loading indicator |
| Multiple Requests | Keys are slightly different (e.g., ['user', '1'] vs ['user', 1]) | Ensure key data types are consistent |
Real-World Examples
1. Fetching a single user
const { data } = useQuery({ queryKey: ['user', id], queryFn: () => getUser(id) })
2. Search with dynamic keyword
const { data } = useQuery({ queryKey: ['search', query], queryFn: () => api.find(query.value) })
3. Automatic page refresh (polling)
const { data } = useQuery({ queryKey: ['stats'], queryFn: getStats, refetchInterval: 3000 })
4. Disabling query until ID is available
const { data } = useQuery({ queryKey: ['x', id], queryFn: getX, enabled: !!id.value })
5. Using Axios (throws automatically)
queryFn: () => axios.get('/api/data').then(res => res.data)
6. Retrying only on specific errors
retry: (count, err) => err.status !== 404 && count < 3
7. Generic fetcher with context
queryFn: ({ queryKey }) => api.get(`/items/${queryKey[1]}`)
8. Sorting a list
const { data } = useQuery({ queryKey: ['posts', { sort: 'desc' }], queryFn: fetchPosts })
9. Showing data from a placeholder
const { data } = useQuery({ queryKey: ['user'], queryFn: getUser, placeholderData: fallbackUser })
10. Manual refresh button
<button @click="refetch()">Reload Data</button>
Visual
The Query Life Cycle
┌──────────────────────────────────────────────────────────┐
│ 1. Component Mounts │
├──────────────────────────────────────────────────────────┤
│ 2. useQuery(['post', 1]) checks Cache │
│ │
│ [ Cache Empty ] [ Cache Hit ] │
│ │ │ │
│ isPending = true isPending = false │
│ isFetching = true isFetching = true │
│ data = undefined data = cached_val │
│ │ │ │
│ (Network Call) (Background Call) │
│ │ │ │
│ 3. SUCCESS ──────────────────────┘ │
│ isFetching = false, isPending = false, data = fresh │
└──────────────────────────────────────────────────────────┘
Query Key Serialization
┌──────────────────────────────────────────────────────────┐
│ ARRAY KEY CACHE STRING (Internal) │
├──────────────────────────────────────────────────────────┤
│ ['user', 5] ──► '["user",5]' │
│ ['user', 10] ──► '["user",10]' │
│ ['posts', {a:1, b:2}] ──► '["posts",{"a":1,"b":2}]'│
└──────────────────────────────────────────────────────────┘
The State Machine (Flags)
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ PENDING │─────►│ SUCCESS │─────►│ FETCHING │
│ (First request) │ │ (Data in cache) │ │ (Bg Update) │
├──────────────────┤ ├──────────────────┤ ├──────────────────┤
│ data: undefined │ │ data: [...] │ │ data: [stale] │
│ isPending: true │ │ isPending: false │ │ isPending: false │
│ isFetching: true │ │ isFetching: false│ │ isFetching: true │
└──────────────────┘ └──────────────────┘ └──────────────────┘
Summary
| Item | Value |
|---|---|
| Identifier | Query Key (Array) |
| Data Fetcher | Query Function (Async/Promise) |
| Initial Loading | isPending |
| Ongoing Activity | isFetching |
| Failure State | isError |
| Primary Output | data |
| Dependency Role | Keys trigger automatic refetching |
| Consistency | Objects in keys are deep-equal |
Key takeaways:
- Query Keys are the unique IDs of your data. Always use an array and include any reactive variable that the query depends on to ensure data stays in sync .
- The Query Function must handle errors. Native
fetchdoesn’t throw on HTTP errors (like 404), so you must manuallythrowto trigger Vue Query’s error state . isPendingvs.isFetching. UseisPendingfor the first-time data load andisFetchingto show background updates when data already exists .- Data is available even during updates. This “Stale-While-Revalidate” behavior is key to a fast UI; avoid showing a blank screen if cached data is already available .
- Keys determine deduplication. Two components using the exact same Query Key will share the same network request and cached data .
- Refetch is your escape hatch. If you need to refresh data outside of the automatic dependency system, the
refetchfunction provides manual control .
Remember: useQuery is a state machine that turns an asynchronous function into a reactive, cached resource. Master the relationship between the Query Key (the ID) and the Query Function (the fetcher), and the library will handle the complex orchestration of loading, errors, and background updates for you.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!