Part 11 / Topic 1 of 5
Loading/error/success: one value, not three flags
A fetch is always in exactly one of three states at any moment: still waiting, failed, or done. The tempting way to model that - three separate useState calls - lets those three booleans disagree with each other, because nothing forces them to be updated together. examples/01_loading_error_success_states.jsx's OrderStatusBooleanSoup has a real version of this bug: it resets isLoading on every fetch but forgets to reset isError:
// examples/01_loading_error_success_states.jsx (boolean soup, trimmed)
export function OrderStatusBooleanSoup({ orderId }) {
const [isLoading, setIsLoading] = useState(true);
const [isError, setIsError] = useState(false);
const [data, setData] = useState(null);
useEffect(() => {
setIsLoading(true);
// BUG: isError is never reset to false here
fetch(`/api/orders/${orderId}`)
.then((res) => { if (!res.ok) throw new Error(`order ${orderId} not found`); return res.json(); })
.then((order) => { setData(order); setIsLoading(false); })
.catch(() => { setIsError(true); setIsLoading(false); });
}, [orderId]);
if (isError) return <p role="alert">Could not load order {orderId}</p>;
if (isLoading) return <p>Loading order {orderId}...</p>;
return <p>Order {data.id}: {data.status}</p>;
}
Mounting this with a bad order id really shows the error, exactly as intended. Changing to a good order id afterward really still shows the error - now reporting the new id, because the message reads the current orderId prop, but still permanently stuck on the error branch, because isError was never reset (examples/01_loading_error_success_states.test.jsx). The order really did load underneath (data is set correctly) - it is simply unreachable, because the three flags no longer describe one consistent story. OrderStatusModeled fixes this by keeping exactly one state value, replaced wholesale on every fetch:
// examples/01_loading_error_success_states.jsx (modeled)
export function OrderStatusModeled({ orderId }) {
const [state, setState] = useState({ phase: "loading" });
useEffect(() => {
setState({ phase: "loading" });
fetch(`/api/orders/${orderId}`)
.then((res) => { if (!res.ok) throw new Error(`order ${orderId} not found`); return res.json(); })
.then((order) => setState({ phase: "success", data: order }))
.catch((error) => setState({ phase: "error", message: error.message }));
}, [orderId]);
if (state.phase === "loading") return <p>Loading order {orderId}...</p>;
if (state.phase === "error") return <p role="alert">{state.message}</p>;
return <p>Order {state.data.id}: {state.data.status}</p>;
}
The identical bad-id-then-good-id sequence on OrderStatusModeled really shows the error, then really shows the correct success message once the second fetch resolves - there is no stale flag left behind to disagree with the new state, because there is no second flag at all.
Done here? The practice set for Part 11 — including the solutions — is on the part page.