Sub topic 10
Dependent and conditional queries
This chapter assumes you can write a basic useQuery call, know what a query key is, and understand the status and fetchStatus fields. It also assumes you have met staleTime and the idea of invalidation. It builds on those to cover queries that must wait for something before they run.
Why a query might need to wait
By default, useQuery fetches as soon as its component mounts. Sometimes that is wrong:
- The request needs a value that another request produces, such as a user id returned by a lookup.
- The request needs input the user has not provided yet, such as a search term or a selected row.
- The request needs a precondition, such as a signed-in session.
If you fire the request anyway, you send a URL like /api/projects?user=undefined. The server returns an error or the wrong data, and the cache stores a failed entry under a key that means nothing. The enabled option prevents this.
The enabled option
enabled is a boolean on the query options. When it is false, the query does not fetch on mount, on window focus, on reconnect, or on an interval. When it becomes true, the query fetches as it normally would.
import { useQuery } from '@tanstack/react-query'
type User = { id: number; name: string }
type Project = { id: number; name: string }
async function fetchUser(email: string): Promise<User> {
const res = await fetch(`/api/users?email=${encodeURIComponent(email)}`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
async function fetchProjects(userId: number): Promise<Project[]> {
const res = await fetch(`/api/projects?userId=${userId}`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
export function UserProjects({ email }: { email: string }) {
const { data: user } = useQuery({
queryKey: ['user', email],
queryFn: () => fetchUser(email),
})
const userId = user?.id
const { data: projects, status, fetchStatus } = useQuery({
queryKey: ['projects', userId],
queryFn: () => fetchProjects(userId!),
enabled: userId !== undefined,
})
return (
<p>
{projects?.length ?? 0} projects ({status}, {fetchStatus})
</p>
)
}The second query is a dependent query. Its key includes userId, so each user gets a separate cache entry. Until userId exists, the query stays idle.
Two details matter here. The non-null assertion userId! is safe only because enabled guarantees the function never runs while userId is undefined. TypeScript cannot see that link, so you must keep the two in sync yourself. Also, the key contains undefined while the query is disabled. That is harmless, but it is a cache entry you did not intend to read.
Reading the state of a disabled query
A disabled query with no cached data has status: 'pending' and fetchStatus: 'idle'. This surprises people who check isPending alone and show a spinner forever. status describes whether you have data. fetchStatus describes whether a request is running.
| Situation | status | fetchStatus |
|---|---|---|
| Disabled, nothing cached | pending | idle |
| Enabled, first request in flight | pending | fetching |
| Data loaded, no request running | success | idle |
| Data loaded, background refetch | success | fetching |
| Request failed | error | idle |
For a dependent query, show a spinner only when a request is actually running. Use isLoading, which is isPending && isFetching:
const projectsQuery = useQuery({
queryKey: ['projects', userId],
queryFn: () => fetchProjects(userId!),
enabled: userId !== undefined,
})
if (projectsQuery.isLoading) return <p>Loading projects...</p>
if (projectsQuery.fetchStatus === 'idle' && projectsQuery.isPending) {
return <p>Waiting for user...</p>
}Conditional queries driven by user input
The same option handles input-driven requests. A search box should not call the server for an empty string or one character:
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
type Result = { id: number; title: string }
async function searchTodos(term: string): Promise<Result[]> {
const res = await fetch(`/api/todos?search=${encodeURIComponent(term)}`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
export function TodoSearch() {
const [term, setTerm] = useState('')
const { data, isFetching } = useQuery({
queryKey: ['todos', 'search', term],
queryFn: () => searchTodos(term),
enabled: term.trim().length >= 3,
})
return (
<div>
<input value={term} onChange={(e) => setTerm(e.target.value)} />
{isFetching && <span>Searching...</span>}
<ul>
{data?.map((r) => (
<li key={r.id}>{r.title}</li>
))}
</ul>
</div>
)
}Each distinct term gets its own cache entry, so typing a term you already searched returns instantly. Typing quickly still creates a request per keystroke once the term is long enough. Debounce the value before putting it in the key if that matters for your server load.
Using skipToken for type-safe disabling
TanStack Query v5 provides skipToken. Instead of a separate enabled flag and a ! assertion, you pass skipToken as the query function when the input is missing:
import { skipToken, useQuery } from '@tanstack/react-query'
type Project = { id: number; name: string }
async function fetchProjects(userId: number): Promise<Project[]> {
const res = await fetch(`/api/projects?userId=${userId}`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
export function useProjects(userId: number | undefined) {
return useQuery({
queryKey: ['projects', userId],
queryFn: userId === undefined ? skipToken : () => fetchProjects(userId),
})
}TypeScript narrows userId to number inside the arrow function, so no assertion is needed. The trade-off is that calling refetch() on a query that uses skipToken fails, because there is no function to run. With enabled: false, a manual refetch() still works.
Common errors
- Using a truthy check that hides valid values.
enabled: !!userIddisables the query whenuserIdis0. Compare againstundefinedornullexplicitly when0is a legal id. - Leaving the dependency out of the key. If
queryKey: ['projects']omitsuserId, every user shares one cache entry, and switching users shows the previous user's data. Anything the query function reads belongs in the key. - Expecting
enabled: falseto be a stop button. Setting it tofalsewhile a request is in flight does not cancel that request. It only stops new fetches from being triggered. - Showing an endless spinner. Checking
isPendingfor a disabled query is always true. CheckisLoadingorfetchStatus. - Building long chains. Three dependent queries run one after another, which creates a request waterfall. If the server can accept the email directly and return projects in one call, add an endpoint rather than chaining.
Combining with the rest of the cache
A disabled query still takes part in invalidation. When a mutation calls invalidateQueries({ queryKey: ['projects'] }), matching queries are marked stale, but only active and enabled ones refetch. A disabled query refetches once it becomes enabled and its data is stale. The cache is shared, so a query enabled elsewhere in the app with the same key fills the data for your component too.
Exercise
A component calls useQuery with queryKey ['orders', customerId], queryFn: () => fetchOrders(customerId!), and enabled: !!customerId. A customer with id 0 exists in the database, and their orders never load. Why, and how would you fix it using both the enabled option and skipToken?
Show answer
The expression !!customerId is false when customerId is 0, so the query stays disabled for that customer. Fix it by comparing against undefined: enabled: customerId !== undefined. With skipToken, write queryFn: customerId === undefined ? skipToken : () => fetchOrders(customerId), which also removes the non-null assertion. With skipToken, remember that refetch() will not work while the id is missing.
Exercise
A disabled query with an empty cache shows a loading spinner forever when you render it on isPending. Which two fields tell you that no request is actually running, and what values do they have?
Show answer
status is 'pending' and fetchStatus is 'idle'. Use isLoading (true only when pending and fetching) to show a spinner, or check fetchStatus === 'idle' to show a waiting message.