Sub topic 4
Modeling loading, error, and success
This chapter assumes you know promises and async/await, React components and JSX, useState, and basic HTTP status codes. You have already seen how to call fetch inside useEffect. Here the focus is on the state that surrounds a request: what to store, how to render it, and which mistakes to avoid.
Why a request has more than one outcome
A request does not return data instantly. Between the moment a component asks for data and the moment it can show it, the user sees something. Your component must decide what that something is.
A request can be in one of three situations:
- Loading: the request was sent and no answer has arrived.
- Error: the request failed, or the server replied with a failure status.
- Success: the response arrived and the body was parsed.
If you render user.name while user is still null, React throws a TypeError and the component crashes. Modeling these three situations explicitly prevents that crash and gives users useful feedback.
The three-variable approach
The most direct model uses one piece of state for each part of the story.
import { useEffect, useState } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const controller = new AbortController();
setIsLoading(true);
setError(null);
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
})
.then((data) => {
setUser(data);
setIsLoading(false);
})
.catch((err) => {
if (err.name === 'AbortError') return;
setError(err);
setIsLoading(false);
});
return () => controller.abort();
}, [userId]);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <h1>{user.name}</h1>;
}Walk through the parts that matter for state modeling:
isLoadingstarts astrue. The first render already shows the loading message, so the user never sees an empty frame.- At the start of each effect run,
setIsLoading(true)andsetError(null)reset the state. Without this reset, a change ofuserIdwould keep showing the previous user's error or data while the new request is in flight. - The
response.okcheck turns HTTP failures into thrown errors. This step is needed because of howfetchbehaves, covered in the next section. - Both the success path and the failure path set
isLoadingtofalse. - The render logic checks
isLoadingfirst, thenerror, then readsuser. The order is what makesuser.namesafe.
Fetch does not reject on 404 or 500
fetch rejects its promise only when the request cannot complete at all, for example when the network is down or the request is aborted. A reply with status 404 or 500 is still a completed exchange, so the promise resolves. Without a check, your code would call response.json() on an error page and either fail with a confusing parse error or store an error body as if it were your data.
response.ok is true for status codes 200 to 299. Checking it and throwing converts "the server said no" into the same error path as "the network failed", so one catch handles both.
The problem with separate booleans
The three-variable model works, but the variables can disagree. Consider the combinations:
| `isLoading` | `error` | `user` | Meaningful? |
|---|---|---|---|
| true | null | null | Yes, first load |
| false | null | object | Yes, success |
| false | Error | null | Yes, failure |
| true | Error | object | No, contradictory |
| false | null | null | No, nothing to show and no reason |
Three variables allow eight combinations, but only three are valid. Every setState call is a chance to produce an invalid one. In the example above, forgetting a single setIsLoading(false) leaves the spinner on forever. Because React batches updates inside event handlers and effects, you also cannot rely on seeing the variables change one at a time, so reasoning about intermediate combinations is a poor use of your attention.
A single status field
A cleaner model stores the situation as one status value and keeps the data and error next to it. Only valid combinations can be expressed, because each update replaces the whole object.
import { useEffect, useState } from 'react';
export function useFetch(url) {
const [state, setState] = useState({ status: 'loading', data: null, error: null });
useEffect(() => {
const controller = new AbortController();
setState({ status: 'loading', data: null, error: null });
fetch(url, { signal: controller.signal })
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
})
.then((data) => setState({ status: 'success', data, error: null }))
.catch((error) => {
if (error.name === 'AbortError') return;
setState({ status: 'error', data: null, error });
});
return () => controller.abort();
}, [url]);
return state;
}This is the same hook you will build up in the chapter on extracting a useFetch hook. Here, look only at the state shape. Each of the three setState calls describes a complete situation. There is no moment when status is 'success' and error is still set.
Rendering becomes a decision on one value:
import { useFetch } from './useFetch';
function UserProfile({ userId }) {
const { status, data, error } = useFetch(`/api/users/${userId}`);
if (status === 'loading') return <p>Loading...</p>;
if (status === 'error') return <p>Error: {error.message}</p>;
return <h1>{data.name}</h1>;
}A fourth value, 'idle', is useful when a request should not start yet, for example before the user submits a search form. You would start in 'idle' and skip the fetch in the effect until its inputs are ready.
Edge cases to decide on purpose
Resetting versus keeping old data
When the input changes, the examples above clear data and show the loading message. This is simple and never shows information that belongs to a different input. The cost is a flash of loading UI on every change, even if the previous data would have been a good placeholder.
Some interfaces prefer to keep showing the old data with a subtle "updating" indicator. That requires holding the previous data while status is loading, and it is a deliberate choice. Libraries such as TanStack Query, covered later, offer it as an option.
Empty results are still success
A successful response with an empty array is not an error and not loading. Handle it as a separate branch inside success:
function UserList({ users }) {
if (users.length === 0) return <p>No users found.</p>;
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}Error messages for users
error.message from a thrown Error is written for developers, such as "Request failed with status 500". Showing it directly is fine in a tutorial. In a product, map known statuses to friendly text and log the technical detail. Also consider giving the user a way to retry, which usually means a button that changes a counter included in the effect's dependency array.
Parse failures
response.json() can reject if the body is not valid JSON, for example when a proxy returns an HTML error page with status 200. Because it sits inside the same promise chain, the catch handles it and the component shows an error instead of crashing.
Updates after unmount
The AbortError check and the cleanup function stop state updates from requests the component no longer cares about. Cancelling is also what keeps the status model honest: a stale response must never move a newer request out of 'loading'. The next chapters on race conditions and cleanup explain why in detail.
Summary of the model
- Represent a request as loading, error, or success, and render each one explicitly.
- Check
response.ok, becausefetchdoes not reject on HTTP error statuses. - Reset the state when inputs change, unless you intentionally keep old data.
- Prefer one
statusfield over several independent booleans so invalid combinations cannot occur. - Treat an empty result as a success case with its own message.
Exercise
A component keeps isLoading, error, and data in three separate useState calls. After a server returns status 503, the page shows "Loading..." forever, and the console shows no error. Name two likely causes and explain how a single status field would help.
Show answer
One likely cause is a missing response.ok check combined with a parse problem, or an error path that never calls setIsLoading(false). In the first case a 503 resolves normally and response.json() may fail or produce unexpected data. In the second, the catch handler sets the error but leaves isLoading as true, and the render checks isLoading first, so the loading message hides the error. With a single status field, the catch handler must call setState({ status: 'error', ... }). That one call changes the whole situation, so the loading state cannot remain set by accident.
Exercise
Why does the render logic in the three-variable example check isLoading and error before reading user.name?
Show answer
Before the response arrives, and after a failure, user is null. Reading user.name then throws a TypeError and crashes the component. Checking isLoading and error first returns early in those cases, so user.name is only reached when user holds the parsed data.