Sub topic 4
Handling pending, error, and success states
This chapter assumes you can write a basic useQuery call and know that fetch returns a Promise. Here you will learn how to render each phase of a request and avoid the most common mistakes.
Two separate pieces of state
A query reports two independent things:
statusdescribes the data:pending(no data yet),error(the last attempt failed), orsuccess(data is available).fetchStatusdescribes the request:fetching,paused(offline), oridle.
They are separate because a query can have data and still be fetching. A background refetch of cached data has status: 'success' and fetchStatus: 'fetching'.
Rendering each state
Each status has a boolean flag: isPending, isError, and isSuccess. Check them in order and return early. TypeScript then narrows the types for you.
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()
}
export function Todos() {
const { data, isPending, isError, error, isFetching } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
})
if (isPending) return <p>Loading...</p>
if (isError) return <p>Something went wrong: {error.message}</p>
return (
<div>
{isFetching && <small>Refreshing...</small>}
<ul>
{data.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
</div>
)
}After the two early returns, data is typed as Todo[], not Todo[] | undefined. The isFetching flag drives a small refresh hint without hiding the list that is already on screen.
Choosing the right flag
| Flag | True when | Typical use |
|---|---|---|
| `isPending` | There is no data yet | Full-screen or skeleton loader |
| `isFetching` | Any request is in flight | Subtle refresh indicator |
| `isLoading` | `isPending` and `isFetching` are both true | Loader that skips paused (offline) queries |
| `isError` | The query function failed and retries ran out | Error message and retry button |
Common errors
fetchdoes not throw on 404 or 500. It only rejects on network failure. If your query function does not checkres.okand throw, the query lands insuccesswith an error body as its data.- Waiting for the default retries. A failing query is retried three times with exponential backoff before it enters
error. During that time the UI still shows the pending state. In tests or for known failures, setretry: falseon the query. - Spinning on
isFetchingalone. This replaces visible cached data with a spinner on every background refetch. UseisPendingfor the first load. - Treating an error as the end of the data. If a background refetch fails,
statusbecomeserror, but the earlierdatais kept. Checkdatabefore discarding a list that was already loaded.
Exercise
A todo list has loaded and is on screen. The user switches tabs and back, and a background refetch starts. Which values do status and fetchStatus have during that refetch, and should the full-screen loader appear?
Show answer
status is success and fetchStatus is fetching. The full-screen loader should not appear, because isPending is false and cached data is available. Show a small indicator based on isFetching instead.