Sub topic 4
Handling pending, error, and success states
This chapter assumes you can fetch data with useQuery (the previous chapter) and are comfortable with React conditional rendering and basic TypeScript unions. By the end you should be able to render every state a query can be in, and explain why a query can be "pending" without anything being on the network.
Two separate questions
A query answers two independent questions:
- status: Do we have data? The values are
pending(no data yet),error(the last attempt failed), andsuccess(data is available). - fetchStatus: Is the query function running right now? The values are
fetching(running),paused(wants to run but cannot, usually because the device is offline), andidle(not running).
TanStack Query keeps these apart because they vary independently. A query that already has cached data can be success and fetching at once, which is a background refetch. A query that is disabled has no data and is not running, so it is pending and idle.
The derived booleans
You rarely compare strings. The result object provides booleans derived from the two values.
| Flag | True when | Typical use |
|---|---|---|
| `isPending` | `status === 'pending'` | No data to show yet |
| `isError` | `status === 'error'` | Show an error message |
| `isSuccess` | `status === 'success'` | Data is available |
| `isFetching` | `fetchStatus === 'fetching'` | Any request is running, including background refetches |
| `isLoading` | `isFetching && isPending` | The first fetch is running |
| `isPaused` | `fetchStatus === 'paused'` | The request is waiting for the network |
| `isRefetching` | `isFetching && !isPending` | A refetch is running over existing data |
Note the difference between isPending and isLoading. isLoading is only true while a request for a query with no data is in flight. For a disabled query, isPending is true forever (until it is enabled), and isLoading is false. If you want "show a spinner", isLoading is accurate. If you want "I cannot read data yet", use isPending.
The basic three-way branch
The standard pattern returns early for pending and error, which leaves the success case at the bottom.
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 query = useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
if (query.status === 'pending') return <p>Loading...</p>
if (query.status === 'error') {
return <p>Something went wrong: {query.error.message}</p>
}
return (
<ul>
{query.data.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)
}Checking query.status against the result object lets TypeScript narrow the type. Inside the success branch, query.data is Todo[], not Todo[] | undefined. In v5 the error field defaults to the type Error, so .message type-checks.
What counts as an error
The query function must throw or return a rejected Promise. fetch does not reject on HTTP 404 or 500, only on network failure, so the if (!res.ok) throw ... line is required. Without it, an error page body would be parsed (or fail to parse) and treated as success.
Before a query reaches error, it retries. The default is three retries with exponential backoff, so a permanently failing query can show the loading state for several seconds before the error appears. During this time failureCount and failureReason on the result tell you what is happening. You can change the behavior per query:
import { useQuery } from '@tanstack/react-query'
declare function fetchReport(): Promise<{ total: number }>
export function Report() {
const { data, isPending, isError } = useQuery({
queryKey: ['report'],
queryFn: fetchReport,
retry: 1,
retryDelay: 500,
})
if (isPending) return <p>Loading...</p>
if (isError) return <p>Could not load the report.</p>
return <p>Total: {data.total}</p>
}Setting retry: false makes the error appear immediately, which is also what you want in most tests.
Errors that arrive after you have data
The early-return pattern has a gap. Suppose a window refocus triggers a refetch and the server is down. The query keeps its old data, but status becomes error. A component that returns the error message for every isError would replace a perfectly usable list with an error screen.
Decide what the user needs. If no data exists, show a full error with a retry button. If data exists, show it and add a smaller warning.
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 ResilientTodos() {
const query = useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
if (query.isPending) return <p>Loading...</p>
if (query.data === undefined) {
return (
<div role="alert">
<p>Could not load todos: {query.error?.message}</p>
<button onClick={() => query.refetch()}>Try again</button>
</div>
)
}
return (
<div>
{query.isError && (
<p role="alert">Could not refresh: {query.error?.message}</p>
)}
{query.isFetching && <small>Updating...</small>}
<ul>
{query.data.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
</div>
)
}The check query.data === undefined after the pending check can only mean "the query failed and never had data". Everything below it has data, so the list renders in both the success and the failed-refetch case. The isFetching flag drives a small background-activity hint without blocking the screen.
Offline and disabled queries
Two situations leave a query in pending without a request running.
- Offline. With the default
networkMode: 'online', a query that wants to fetch while the browser is offline becomespendingwithfetchStatus: 'paused'. It resumes when the connection returns. If you only render "Loading..." forisPending, the user sees an endless spinner while offline. Checkquery.isPausedand show "Waiting for connection" instead. - Disabled. With
enabled: false, the query ispendingandidle. A later chapter covers this in detail. For now, remember thatisPendingalone does not mean a request is running. UseisLoadingwhen you need that.
Common mistakes
- Reading
databefore checking status.dataisundefinedwhile pending, sodata.map(...)throws on the first render. - Forgetting to throw on
!res.ok. The query reportssuccesswith an error body as its data. - Using
isLoadingas the guard fordata. A disabled query hasisLoading === falseanddata === undefined, so the component crashes. Guard withisPendingor adatacheck. - Replacing good data with an error screen on a failed refetch. Check
databefore you decide that the whole view failed. - Waiting through retries in tests. Three retries with backoff makes error tests slow or time out. Set
retry: falseon the test client.
Exercise
A query is created with enabled: false and has never run. What are its status, fetchStatus, isPending, and isLoading values, and why is isLoading different from isPending here?
Show answer
status is pending, fetchStatus is idle, isPending is true, and isLoading is false. isPending only says that no data exists. isLoading is isFetching && isPending, and nothing is fetching, so it is false. Reading data is still unsafe because it is undefined.
Exercise
A user has a list on screen. They switch tabs, return, and the automatic refetch fails with a 500. What are status, isError, and data afterwards, and how should the component render?
Show answer
status is error, isError is true, and data still holds the previous list. The component should keep rendering the list and show a small warning (for example "Could not refresh"), instead of replacing the list with a full error screen. A full error screen is only right when data is undefined.