Sub topic 10
Dependent and conditional queries
This chapter assumes you can write a basic useQuery call and that you understand query keys and query status. Some queries can't run until something else exists. Examples are a user id that comes from another request, or a search term the user hasn't typed yet. The enabled option handles these cases.
Why a query may need to wait
A query runs as soon as its component mounts. If the query function needs a value that is still undefined, the request goes out with bad input, such as /api/projects/undefined.
Setting enabled: false stops the query from fetching. While the query is disabled, it doesn't fetch on mount and it doesn't refetch in the background. When enabled turns true, it fetches normally.
A dependent query
Two queries are dependent when the second needs data from the first. The second query's key includes the value it depends on, and enabled holds it back until that value exists.
import { useQuery } from '@tanstack/react-query'
type User = { id: number; name: string }
type Project = { id: number; name: string }
declare function fetchUser(email: string): Promise<User>
declare function fetchProjects(userId: number): Promise<Project[]>
function UserProjects({ email }: { email: string }) {
const { data: user } = useQuery({
queryKey: ['user', email],
queryFn: () => fetchUser(email),
})
const userId = user?.id
const { data: projects } = useQuery({
queryKey: ['projects', userId],
queryFn: () => fetchProjects(userId!),
enabled: userId !== undefined,
})
return <p>{projects?.length ?? 0} projects</p>
}Here is what happens, step by step:
- The first render starts the user query.
userIdisundefined, so the projects query stays disabled. - The user request succeeds and
userIdgets a value. enabledbecomestrue, and the projects query fetches with that id.
The userId! non-null assertion is safe only because enabled guards the call. TypeScript can't see that link, so you assert it yourself.
Reading the status of a disabled query
A disabled query that has no cached data stays in the pending status. Its fetchStatus is idle, because nothing is being fetched. This matters for loading spinners. If you show a spinner whenever isPending is true, a disabled query shows it forever.
Use isLoading instead. It is true only when the status is pending and the query is actually fetching.
import { useQuery } from '@tanstack/react-query'
function SearchResults({ term }: { term: string }) {
const { data, isLoading } = useQuery({
queryKey: ['search', term],
queryFn: async () => {
const res = await fetch(`/api/search?q=${encodeURIComponent(term)}`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json() as Promise<string[]>
},
enabled: term.length >= 3,
})
if (term.length < 3) return <p>Type at least 3 characters.</p>
if (isLoading) return <p>Searching...</p>
return (
<ul>
{data?.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
)
}Common errors
- Leaving a dependency out of the key. If
userIdisn't in the key, two users share one cache entry. - Using
isPendingfor a spinner on a disabled query. The spinner never goes away. - Treating
enabledas a security check. It only controls fetching on the client. The server must still check permissions. - Using
0or''as a "missing" value with a truthiness test.enabled: !!userIdisfalsefor a valid id of0. Compare againstundefinedwhen0is a real value.
Exercise
A query has enabled: false and no cached data. What are its status and fetchStatus, and which flag should you use to show a loading spinner?
Show answer
The status is pending and the fetchStatus is idle. Use isLoading, which is true only while the query is pending and fetching. isPending would stay true for as long as the query is disabled.