Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 25 min · revision 2

Fetching Data Safely Inside Components

Fetch server data from an effect without race conditions, model loading, empty and error states explicitly, and contain failures with an error boundary that can retry.

Contentsand lesson path

What you will learn

  • Fetch server data in components without race conditions, rendering loading, error and empty states and recovering with an error boundary.

Prerequisites: React Components & State, Async JavaScript & Fetch

01. The problem

Fetching in an effect is the standard way a client-rendered component talks to a server: the component mounts, the effect starts the request, the response lands in state. It is also the pattern with the most ways to go wrong, because the network adds three things rendering never has: latency (the screen needs something to show meanwhile), ordering (an older request can answer after a newer one) and failure (the request can fail and the component must still render).

The fetch mechanics themselves are old ground — read the fetching lesson of the asynchronous JavaScript skill if the fetch calls below feel unfamiliar. What is new here is React-shaped: which state models the request, how the effect's cleanup defuses out-of-order responses, and where a rendering crash is allowed to land. Everything runs against a small local API so the outcomes are reproducible.

JS · mock-api.mjs (excerpt: search endpoint of the local books API)
import { createServer } from 'node:http';

const BOOKS = [
  { id: 1, title: 'React Quickstart', author: 'Ada Fields' },
  { id: 2, title: 'React Patterns', author: 'Grace Oduya' },
  { id: 3, title: 'Refactoring UIs', author: 'Lin Mao' },
  { id: 4, title: 'REST in Practice', author: 'Sam Yates' },
  { id: 5, title: 'JavaScript: The Good Bits', author: 'Ana Duarte' },
];
// Scripted latencies: "re" answers after 200 ms, "react" after 50 ms —
// so an older request can settle last. That is the race this lesson fixes.
const DELAYS = { '': 80, re: 200, react: 50 };
let brokenPayload = false;
let failOk = false;

createServer((req, res) => {
  const url = new URL(req.url, 'http://localhost');
  const send = (status, body) => {
    res.writeHead(status, {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
    });
    res.end(JSON.stringify(body));
  };
  if (req.method === 'OPTIONS') {
    res.writeHead(204, {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
    });
    return res.end();
  }
  if (req.method === 'POST' && url.pathname === '/api/__control') {
    let raw = '';
    req.on('data', (c) => (raw += c));
    req.on('end', () => {
      const body = JSON.parse(raw);
      brokenPayload = Boolean(body.brokenPayload);
      failOk = Boolean(body.failOk);
      send(200, { ok: true });
    });
    return;
  }
  if (url.pathname !== '/api/books') return send(404, { error: 'Not found' });
  const q = (url.searchParams.get('q') ?? '').trim().toLowerCase();
  if (q === 'fail' && !failOk) {
    return setTimeout(() => send(500, { error: 'Search is down' }), 20);
  }
  const results = brokenPayload
    ? null
    : BOOKS.filter((b) => b.title.toLowerCase().includes(q));
  setTimeout(() => send(200, { query: q, results }), DELAYS[q] ?? 40);
}).listen(4001);

Start the server with node mock-api.mjs and pass its address to the components below as apiBase="http://localhost:4001" (port 4001 avoids colliding with Vite preview on 4173). The transcripts below come from rendering each component in a Vite page and driving it in Chromium with Playwright; the race transcripts type "react" 80 ms after the "re" request starts. By hand, paste "react" into the box quickly to see the same order. Three behaviours matter: the scripted delays make "re" slower than "react", the query "fail" answers HTTP 500 until the control endpoint is told otherwise, and the same endpoint can be switched to send a malformed payload with results: null.

02. Step 1: watch the race happen

JSX · book-search-buggy.jsx
import { useEffect, useState } from 'react';

export default function BookSearchBuggy({ apiBase }) {
  const [query, setQuery] = useState('re');
  const [books, setBooks] = useState([]);
  useEffect(() => {
    fetch(`${apiBase}/api/books?q=${encodeURIComponent(query)}`)
      .then((res) => res.json())
      .then((data) => setBooks(data.results));
  }, [query, apiBase]);
  return (
    <>
      <label>
        Search books
        <input value={query} onChange={(e) => setQuery(e.target.value)} />
      </label>
      <ul>
        {books.map((b) => (
          <li key={b.id}>{b.title}</li>
        ))}
      </ul>
    </>
  );
}
Expected output (every change of the list, in order; long line wrapped)
typed "react" while the "re" request is still in flight
input "react" -> list: React Quickstart, React Patterns
input "react" -> list: React Quickstart, React Patterns, Refactoring UIs,
  REST in Practice

The script: the component mounts with the query "re", whose request needs 200 ms; 80 ms later the user types "react", starting a second request that needs only 50 ms. The newer response lands first and the list briefly shows the right two books. Then the older response lands — and this component has no idea it is out of date, so it overwrites the correct answer with the results for a query the user has already left behind.

For a moment the screen was right, then it went wrong. That is what makes the race nasty: tests that only check the final state too late, or too early, miss it entirely. The fix must live in the effect's own lifecycle.

03. Step 2: the ignore flag

JSX · book-search-fixed.jsx
  useEffect(() => {
    let ignore = false;
    fetch(`${apiBase}/api/books?q=${encodeURIComponent(query)}`)
      .then((res) => res.json())
      .then((data) => {
        if (!ignore) setBooks(data.results);
      });
    return () => {
      ignore = true;
    };
  }, [query, apiBase]);
Expected output (same script as step 1; the late "re" response changes nothing)
typed "react" while the "re" request is still in flight
input "react" -> list: React Quickstart, React Patterns

The cleanup flips the flag the moment React re-runs the effect — which is exactly when the previous request became obsolete. When the slow "re" response finally arrives, its callback reads ignore, sees it is true, and returns without touching state. Stale data can no longer win, whatever the network does.

Development Strict Mode adds a free test: on mount the effect runs, cleans up and runs again, so the very first response arrives at a component whose flag is already true and is dropped. If your fetch survives Strict Mode, the flag is doing its job. (This is also why "my effect fires twice in development" is not, by itself, a bug report.)

04. Step 3: cancel the request itself

JSX · book-search-abort.jsx
  useEffect(() => {
    const controller = new AbortController();
    fetch(`${apiBase}/api/books?q=${encodeURIComponent(query)}`, {
      signal: controller.signal,
    })
      .then((res) => res.json())
      .then((data) => setBooks(data.results))
      .catch((error) => {
        if (error.name !== 'AbortError') throw error;
      });
    return () => controller.abort();
  }, [query, apiBase]);
Expected output (same script as step 1; the "re" request is cancelled)
typed "react" while the "re" request is still in flight
input "react" -> list: React Quickstart, React Patterns

Same outcome on screen, different mechanics: the cleanup calls controller.abort(), so the browser stops the stale request instead of waiting for an answer it will drop — you can see it listed as cancelled in the network panel. The aborted fetch rejects with an AbortError, which the catch swallows; any other error is rethrown and surfaces as an unhandled promise rejection in the console — acceptable in a demo, and exactly what step 4 replaces with an error status. Reach for the flag when you only need correctness, and for the controller when stale requests are large enough to be worth stopping. The cancellation lesson of the asynchronous JavaScript skill covers AbortController outside React.

05. Step 4: one status at a time

Correct results are not enough if the screen has nothing to say while they travel, or when they fail. Model the whole lifecycle with one state holding a status — and note that it starts at loading, not at an empty list, so the screen never confuses "not yet" with "nothing":

JSX · status-search.jsx (state and effect)
function toStatus(data) {
  if (data.results === null) {
    return { type: 'error', message: 'the server sent malformed data' };
  }
  if (data.results.length === 0) {
    return { type: 'empty' };
  }
  return { type: 'success', results: data.results };
}

export default function StatusSearch({ apiBase, initialQuery = '' }) {
  const [query, setQuery] = useState(initialQuery);
  const [attempt, setAttempt] = useState(0);
  const [status, setStatus] = useState({ type: 'loading' });

  useEffect(() => {
    let ignore = false;
    setStatus({ type: 'loading' });
    fetch(`${apiBase}/api/books?q=${encodeURIComponent(query)}`)
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      })
      .then((data) => {
        if (!ignore) setStatus(toStatus(data));
      })
      .catch((error) => {
        if (!ignore) setStatus({ type: 'error', message: error.message });
      });
    return () => {
      ignore = true;
    };
  }, [query, attempt, apiBase]);
JSX · status-search.jsx (rendering each status)
  return (
    <>
      <label>
        Search books
        <input value={query} onChange={(e) => setQuery(e.target.value)} />
      </label>
      {status.type === 'loading' && <p role="status">Loading books…</p>}
      {status.type === 'empty' && (
        <p>No books match &quot;{query}&quot;. Try another word.</p>
      )}
      {status.type === 'error' && (
        <p role="alert">
          Something went wrong: {status.message}.{" "}
          <button type="button" onClick={() => setAttempt((a) => a + 1)}>
            Retry
          </button>
        </p>
      )}
      {status.type === 'success' && (
        <ul>
          {status.results.map((b) => (
            <li key={b.id}>{b.title}</li>
          ))}
        </ul>
      )}
    </>
  );
}
Expected output (walking the statuses)
mount, query "react"        -> "Loading books…"
response arrives            -> list: React Quickstart, React Patterns
query "zzz"                 -> "No books match "zzz". Try another word."
query "fail"                -> "Something went wrong: HTTP 500. Retry"
click "Retry" (server ok)   -> "No books match "fail". Try another word."

Three details carry the design. The status lives in one piece of state, so the screen can never show a list and an error at the same time. The loading status is announced with role="status" so screen readers hear it, and the error with role="alert". And retry is just a dependency: attempt sits in the array, so clicking Retry re-runs the effect for the same query — visible in the recording, where the healed server answers "fail" with an empty result and the empty status takes over.

06. Step 5: contain crashes with an error boundary

Statuses handle expected failure. A crash is different: if rendering throws — say the payload shape surprises you and the code reads a property of null — React unmounts the whole tree on the way out. An error boundary is a component that catches errors from rendering its children and shows a fallback instead. A try/catch cannot do this job: placed around JSX it only wraps the act of creating elements, not React's later rendering of them.

JSX · widget-boundary.jsx and book-count-widget.jsx
import { Component } from 'react';

export default class WidgetBoundary extends Component {
  state = { failed: false };

  static getDerivedStateFromError() {
    return { failed: true };
  }

  render() {
    if (this.state.failed) {
      return (
        <p role="alert">
          This panel failed to render.{" "}
          <button type="button" onClick={this.props.onRetry}>
            Retry
          </button>
        </p>
      );
    }
    return this.props.children;
  }
}

// The widget: a fetch whose malformed answer crashes its render.
import { useEffect, useState } from 'react';

export default function BookCountWidget({ apiBase }) {
  const [data, setData] = useState(null);
  useEffect(() => {
    fetch(`${apiBase}/api/books`)
      .then((res) => res.json())
      .then(setData);
  }, [apiBase]);
  if (data === null) {
    return <p role="status">Counting books…</p>;
  }
  return <p>The catalogue lists {data.results.length} books.</p>;
}
JSX · the panel that contains the crash
function Panel({ apiBase }) {
  const [attempt, setAttempt] = useState(0);
  return (
    <>
      <p>Search stays usable.</p>
      <WidgetBoundary key={attempt} onRetry={() => setAttempt((a) => a + 1)}>
        <BookCountWidget apiBase={apiBase} />
      </WidgetBoundary>
    </>
  );
}
Expected output (malformed payload, then a healed server)
payload {results: null}     -> alert "This panel failed to render. Retry"
rest of the page            -> "Search stays usable."
click "Retry" (server ok)   -> "The catalogue lists 5 books."

With results: null in the payload, data.results.length throws during render. The boundary catches it and swaps only its subtree for the fallback — the paragraph next to it keeps rendering. The key={attempt} on the boundary is the reset mechanism: bumping attempt remounts the boundary and its child, clearing the failure state, and the widget fetches again. Once the server is healed, retry recovers; nothing outside the panel ever noticed. Boundaries do not catch errors in event handlers or in asynchronous code (promise callbacks such as fetch().then, timers), which is where a fetch inside an effect fails — those failures stay in the code that caused them, which is why the status machine above handles fetch errors itself.

07. Common mistakes

08. Check your understanding

Practice check · 3 questions

Fetching under pressure

Decide what the code does before you ship it.

Q1. In the fixed search, the response for the older query arrives after React already ran that effect's cleanup. What does the component do with it?
Q2. What does AbortController add over the ignore flag alone?
Q3. Your dashboard wraps several widgets in an error boundary. Which failure will it still let through?
Practice only: not graded, not saved, not evidence.

09. Apply it

Build the search page for the book-search practice project on the status machine from this lesson:

  1. Wire StatusSearch to your API and add a debounced query so typing fires fewer requests.
  2. Kill your server (or point apiBase at a dead port) and confirm the error status and Retry behave.
  3. Add an error boundary around one panel and break its data shape on purpose; confirm the rest of the page survives and retry recovers.
  4. Check the keyboard path: the input, the Retry button and the boundary's fallback must all be reachable without a mouse.

10. Review prompt

Without looking back: script the race in words — which request must still be in flight when the user types, and which response must land last? What exactly does the ignore flag flip, and when? Why does the status state start at loading rather than an empty list? Where do boundaries catch errors, and where not? And how does the Retry button re-run an effect without changing the query?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check