Skip to content

Loading Data

The Course
•
30 min study

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 promise pauses only the current function until the answer arrives, then gives you the value. If the promise rejects, await throws its error, so a try/catch around it catches a failed request.
  • await only works inside a function marked async. An async function always returns a promise itself.

Predict the order of the four lines this prints, then run it:

Predict the order JavaScript
// 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
Text
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:

JavaScript
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

Loading, failed, ready React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server. The lab can't use the network, so these functions wait, // like a real request would, and then return data or fail. const topics = [ { id: 1, title: "Components", summary: "Functions that return JSX." }, { id: 2, title: "State", summary: "A component's memory between renders." }, { id: 3, title: "Effects", summary: "Code that keeps something outside React in step." }, ]; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export async function fetchTopics({ fail = false } = {}) { await wait(600); if (fail) throw new Error("The server didn't answer. Try again."); return topics.map(({ id, title }) => ({ id, title })); } // Topic 1 answers slowly and topic 3 quickly, like a real server sometimes does. export async function fetchTopic(id) { await wait(id === 1 ? 1200 : id === 2 ? 600 : 200); const topic = topics.find((t) => t.id === id); if (!topic) throw new Error(`No topic with id ${id}.`); return topic; } import { useEffect, useState } from "react"; import { fetchTopics } from "./api.js"; export default function App() { const [topics, setTopics] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { async function load() { try { const data = await fetchTopics({ fail: false }); setTopics(data); } catch (err) { setError(err.message); } finally { setLoading(false); } } load(); }, []); if (loading) return <p>Loading topics…</p>; if (error) return <p className="error">{error}</p>; return ( <main> <h1>Topics</h1> <ul> {topics.map((topic) => ( <li key={topic.id}>{topic.title}</li> ))} </ul> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; } .error { color: #b42318; padding: 0 1rem; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Press Run and watch for Loading topics… before the list appears.

Load in an effect

JavaScript
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. An async function returns a promise, and React expects an effect to return nothing or a cleanup function. So the effect defines an async function and calls it.
  • try, catch and finally cover 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

JSX
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

Exercise

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.

Your working space React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server. The lab can't use the network, so these functions wait, // like a real request would, and then return data or fail. const topics = [ { id: 1, title: "Components", summary: "Functions that return JSX." }, { id: 2, title: "State", summary: "A component's memory between renders." }, { id: 3, title: "Effects", summary: "Code that keeps something outside React in step." }, ]; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export async function fetchTopics({ fail = false } = {}) { await wait(600); if (fail) throw new Error("The server didn't answer. Try again."); return topics.map(({ id, title }) => ({ id, title })); } // Topic 1 answers slowly and topic 3 quickly, like a real server sometimes does. export async function fetchTopic(id) { await wait(id === 1 ? 1200 : id === 2 ? 600 : 200); const topic = topics.find((t) => t.id === id); if (!topic) throw new Error(`No topic with id ${id}.`); return topic; } import { useEffect, useState } from "react"; import { fetchTopics } from "./api.js"; export default function App() { const [topics, setTopics] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { async function load() { try { const data = await fetchTopics({ fail: false }); setTopics(data); } catch (err) { setError(err.message); } finally { setLoading(false); } } load(); }, []); if (loading) return <p>Loading topics…</p>; if (error) return <p className="error">{error}</p>; return ( <main> <h1>Topics</h1> <ul> {topics.map((topic) => ( <li key={topic.id}>{topic.title}</li> ))} </ul> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; } .error { color: #b42318; padding: 0 1rem; }
Runs with Vite on your computer: unzip, then 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
JavaScript
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]);
JSX
if (error) {
  return (
    <p className="error">
      {error} <button onClick={() => setAttempt(attempt + 1)}>Try again</button>
    </p>
  );
}

Was this article helpful?

Your response is saved on this device.