Most apps load their data from a server. The request takes time and can fail, so a component that loads data has three states to show: loading, failed, and ready.
A pretend server
The labs can't use the network, so src/api.js pretends to be a server. Its
functions wait a little, like a real request, and then return data or throw an
error. On your own computer you'd call fetch instead; the React side stays
the same.
Waiting for an answer
A request to a server doesn't answer straight away, and JavaScript doesn't stop
and wait for it: the rest of the page keeps working. So a function such as
fetchTopics() can't return the topics. It returns a promise instead: an
object that stands for "the answer, when it arrives". Later the promise either
resolves with a value or rejects with an error.
Two keywords make promises read like ordinary code:
await promisepauses only the current function until the answer arrives, then gives you the value. If the promise rejects,awaitthrows its error, so atry/catcharound it catches a failed request.awaitonly works inside a function markedasync. Anasyncfunction always returns a promise itself.
Predict the order of the four lines this prints, then run it:
// A pretend server: it answers after half a second, or fails.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function fetchScore(fail) {
await wait(500);
if (fail) throw new Error("The server didn't answer.");
return 42;
}
async function show(fail) {
try {
const score = await fetchScore(fail);
console.log("score:", score);
} catch (err) {
console.log("failed:", err.message);
}
}
console.log("asking twice");
show(false);
show(true);
console.log("asked, but no answers yet");Check your prediction
asking twice
asked, but no answers yet
score: 42
failed: The server didn't answer.Both show calls start, reach await, and pause. The last console.log runs
straight away. Half a second later the answers arrive: one resolves with 42,
the other rejects, and its catch runs.
You'll also see the same thing written with .then and .catch, which take
functions to call when the answer arrives:
fetchScore(true)
.then((score) => console.log("score:", score))
.catch((err) => console.log("failed:", err.message));It prints the same as show(true). await with try/catch reads better when
there are several steps; .then is shorter for one. React code uses both, and
so does this day.
Three states
npm install and npm run dev. Press Run and watch for Loading topics… before the list appears.
Load in an effect
useEffect(() => {
async function load() {
try {
const data = await fetchTopics({ fail: false });
setTopics(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
load();
}, []);- The dependency list is empty, so the data loads once, when the component first appears.
- The effect function itself can't be
async. Anasyncfunction returns a promise, and React expects an effect to return nothing or a cleanup function. So the effect defines anasyncfunction and calls it. try,catchandfinallycover the three states: success stores the data, failure stores a message, and either way loading has finished.
This first version focuses on the three display states. It doesn't yet ignore an answer after the component is removed. The next lesson adds cleanup for that case and for requests that finish out of order.
Three states, three returns
if (loading) return <p>Loading topics…</p>;
if (error) return <p className="error">{error}</p>;Early returns keep each state separate and easy to read. Only the last
return deals with the data.
Predict: a failing server
Change { fail: false } to { fail: true } and run. What do you see, and in
what order?
Check your prediction
Loading topics… for a moment, then The server didn't answer. Try again.
in red. The error came from api.js's throw, which made the promise reject.
await threw that error inside load, and catch caught it.
Change it back to false.
Your turn
A Try again button
With fail: true, there's no way to recover except reloading. Add a Try
again button to the error state that loads the topics again. To see it work,
make only the first attempt fail.
npm install and npm run dev. Hint 1: the idea
An effect runs again when a dependency changes. Add an attempt number to
state, put it in the dependency list, and have the button increase it.
Hint 2: a first step
Pass { fail: attempt === 0 }. At the start of the effect, set loading back
to true and clear the error, so the retry shows Loading topics… again.
Show one solution
const [attempt, setAttempt] = useState(0);
useEffect(() => {
async function load() {
setLoading(true);
setError(null);
try {
const data = await fetchTopics({ fail: attempt === 0 });
setTopics(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
load();
}, [attempt]);if (error) {
return (
<p className="error">
{error} <button onClick={() => setAttempt(attempt + 1)}>Try again</button>
</p>
);
}Completion is saved in this browser only. It does not measure mastery.