Sub topic 3
Fetching data with useQuery
This chapter assumes you know TypeScript, async/await, React function components and hooks, and how to call a JSON API with fetch. It also assumes you have already placed a QueryClientProvider at the top of your app, as shown in the previous chapter.
What useQuery does
useQuery reads server data into a component. You give it two things:
- A query key, an array that identifies the data in the cache.
- A query function, an async function that fetches the data and returns a Promise.
TanStack Query runs the function, stores the result in the cache under the key, and re-renders your component as the request moves from loading to done.
A first query
import { useQuery } from '@tanstack/react-query'
type Todo = { id: number; title: string; done: boolean }
async function fetchTodos(): Promise<Todo[]> {
const res = await fetch('/api/todos')
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
function Todos() {
const { data, isPending, isError, error } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
})
if (isPending) return <p>Loading...</p>
if (isError) return <p>Something went wrong: {error.message}</p>
return (
<ul>
{data.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)
}The hook takes a single options object. It returns an object with the request state, and the code above reads four fields from it:
datais the result of the query function. It isundefineduntil the first success.isPendingistruewhile there is no data yet.isErroristruewhen the query function failed.errorholds the thrown error.
Checking isPending and isError first lets TypeScript narrow data to Todo[] in the final return.
The query function must throw
fetch only rejects on network failures. A 404 or 500 response resolves normally. TanStack Query decides a query failed only if the query function throws or returns a rejected Promise. That is why fetchTodos checks res.ok and throws. If you skip this check, an error response body gets cached as if it were valid data.
What happens when the component mounts
If another component already requested ['todos'], useQuery returns the cached data at once. Two components that use the same key share one cache entry and trigger one request, not two.
Common mistakes
- Using
fetchwithout ares.okcheck, so HTTP errors look like successes. - Calling the function in
queryFn: fetchTodos()instead of passing it. Pass the function itself, or wrap it as() => fetchTodos(). - Copying
dataintouseState. The cache is already the source of truth, so readdatadirectly.
Exercise
A request to /api/todos returns status 500, and your query function is async () => (await fetch('/api/todos')).json(). Why does the component never show its error message, and how do you fix it?
Show answer
fetch resolves for a 500 response, so the query function does not throw and the query counts as a success. Check res.ok and throw an error (for example throw new Error(Request failed: ${res.status})) before calling res.json().