Sub topic 4
Modeling loading, error, and success
This chapter assumes you know useState, promises and async/await, and how useEffect runs a fetch when its dependencies change. Here you will decide how a component represents the three things a request can be doing: waiting, failing, or succeeding.
Why three states
A request is never just "data or no data". While it is in flight, the screen needs something to show. If it fails, the user needs to know. Only after success is there data to render. A component that tracks only data cannot tell "still loading" from "loaded, but empty", so it flashes wrong content or crashes on null.
Separate state variables
The most direct model uses one useState per concern.
import { useEffect, useState } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
setIsLoading(true);
setError(null);
fetch(`/api/users/${userId}`)
.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) => {
setError(err);
setIsLoading(false);
});
}, [userId]);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <h1>{user.name}</h1>;
}Three details matter here.
- The effect resets
isLoadinganderrorat the start. Without this, a change ofuserIdwould keep showing the previous error. fetchonly rejects on network failure. A 404 or 500 still resolves, so the code checksresponse.okand throws. That sends HTTP errors to the same.catchas network errors.- The render order is loading, then error, then success. Checking in this order guarantees
useris notnullwhenuser.nameruns.
Impossible combinations
Separate variables allow states that should not exist, such as isLoading true and error set at once. Each setState call is a chance to forget one. A single status field removes the problem, because it can only hold one value.
import { useEffect, useState } from 'react';
function UserName({ userId }) {
const [state, setState] = useState({ status: 'loading', data: null, error: null });
useEffect(() => {
setState({ status: 'loading', data: null, error: null });
fetch(`/api/users/${userId}`)
.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) => setState({ status: 'error', data: null, error }));
}, [userId]);
if (state.status === 'loading') return <p>Loading...</p>;
if (state.status === 'error') return <p>Error: {state.error.message}</p>;
return <h1>{state.data.name}</h1>;
}Common mistakes
- Starting with
isLoadingasfalse. The first render then briefly shows the success branch with no data. - Forgetting
response.ok, so a 500 response is parsed as if it were good data. - Not clearing the old error when the request restarts.
- Reading
data.namebefore checking the status.
Exercises
Exercise
Why does the first example check response.ok instead of relying on .catch alone?
Show answer
fetch rejects only when the request cannot complete, such as a network failure. A 404 or 500 response still resolves normally, so without the response.ok check the error status would be treated as success. Throwing an error when response.ok is false routes HTTP errors to .catch.
Exercise
What problem does a single status field solve compared with separate isLoading, error, and data variables?
Show answer
It makes contradictory combinations, such as loading and error at the same time, impossible. Every update sets the whole state at once, so the variables cannot drift out of sync.