Sub topic 9
Modeling async work: loading, success, error
This chapter assumes you know JavaScript promises and fetch, React function components, useEffect, and the basics of useReducer and dispatch from earlier chapters. You will model a network request as a small state machine and keep the reducer pure.
Why separate useState calls drift
A common first attempt uses three useState calls: loading, data, and error. Each response needs several setter calls, and it is easy to leave the fields disagreeing. For example, a retry may set loading to true while the old error is still on screen.
A reducer fixes this. One action changes all related fields at once, so the state is always consistent.
One status field, not several booleans
Use a single status field with a fixed set of values. Pair it with data and error.
| status | data | error | What the UI shows |
|---|---|---|---|
| `idle` | `null` | `null` | Nothing yet |
| `loading` | `null` | `null` | A spinner |
| `success` | the result | `null` | The result |
| `error` | `null` | a message | The message |
This avoids impossible combinations such as loading: true and error: 'Failed' at the same time.
The reducer only records what happened
Each action name describes an event: fetch_started, fetch_succeeded, fetch_failed. The reducer does not call fetch. It only computes the next state from the current state and the action.
import { useEffect, useReducer } from 'react';
const initialState = { status: 'idle', data: null, error: null };
function fetchReducer(state, action) {
switch (action.type) {
case 'fetch_started':
return { status: 'loading', data: null, error: null };
case 'fetch_succeeded':
return { status: 'success', data: action.data, error: null };
case 'fetch_failed':
return { status: 'error', data: null, error: action.error };
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function User({ url }) {
const [state, dispatch] = useReducer(fetchReducer, initialState);
useEffect(() => {
let ignore = false;
dispatch({ type: 'fetch_started' });
fetch(url)
.then(res => {
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
})
.then(data => {
if (!ignore) dispatch({ type: 'fetch_succeeded', data });
})
.catch(error => {
if (!ignore) dispatch({ type: 'fetch_failed', error: error.message });
});
return () => {
ignore = true;
};
}, [url]);
if (state.status === 'loading') return <p>Loading...</p>;
if (state.status === 'error') return <p>Error: {state.error}</p>;
if (state.status === 'success') return <pre>{JSON.stringify(state.data, null, 2)}</pre>;
return null;
}The side effect lives in useEffect. The reducer stays pure, so it can run twice in Strict Mode without causing a second request.
Walking through the effect
- On mount, and whenever
urlchanges, the effect dispatchesfetch_started. The status becomesloadingand any old data or error is cleared. - The request runs. A non-2xx response is turned into an error, because
fetchonly rejects on network failures. - A successful parse dispatches
fetch_succeededwith the data on the action. - Any thrown error reaches
catchand dispatchesfetch_failedwith the message.
Guarding against stale responses
Suppose url changes while a request is in flight. Without protection, the older response could arrive last and overwrite the newer one. The ignore flag prevents that. React runs the cleanup function before the next effect, which sets ignore to true for the old request. Its late result is then dropped.
The same guard handles Strict Mode in development, where React mounts, unmounts, and remounts a component. The first request is ignored and the second one is used.
Common errors
- Storing the error object. Error objects do not serialize well and are awkward to compare. Store
error.message, as shown above. - Forgetting
res.ok. A 404 still resolves the promise. Without the check, you would dispatch success with an error page body. - Missing cleanup. Without
ignore, fast URL changes can show data for the wrong URL. - Keeping stale data on retry. This reducer clears
dataonfetch_started. If you want to show old data while refreshing, return{ ...state, status: 'loading' }instead.
Exercise
A user clicks "Retry" after a failed request, and your code dispatches fetch_started. With the reducer above, what are status, data, and error right after that dispatch, and why can the UI never show both a spinner and the old error?
Show answer
status is 'loading', data is null, and error is null. The fetch_started case returns a whole new state object that resets all three fields together. Because every action replaces the related fields at once, and the UI branches on status, the old error cannot remain visible while loading is shown.
Exercise
Why does the effect check ignore before dispatching fetch_succeeded or fetch_failed?
Show answer
When url changes or the component unmounts, React runs the cleanup function, which sets ignore to true for the old request. If that old request finishes later, the check stops it from dispatching, so a stale response cannot overwrite the state for the newer URL.