Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.7 — Fetching Data in an Effect
React · Example 1 of 4

Loading, error and success

User 1 loads, then the script picks user 3, who doesn't exist. key={userId} gives each user a fresh Profile starting at loading (Topic 7.6), so the old user's name never shows under the new id. role="alert" makes screen readers announce the error.

You can load data in an effect by tracking loading, error and success states, but you must stop old responses from overwriting new ones (a race condition) with an ignore flag or an AbortController; in real apps a framework or a data library usually does this better.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a useEffect that loads /api/posts?page= + page with fetch, ignores stale responses, and stores the JSON in posts.

02

Rewrite the previous answer with AbortController.

Explain it without notes

01

How would you fetch data in a useEffect? Cover loading, error and success.

02

Describe a race condition in data fetching and two ways to prevent it.

03

Why can't the effect function be async?

04

Why do frameworks and data libraries usually fetch better than hand-written effects?

Loading, error and success

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

render user 1 -> loading
render user 1 -> success
render user 3 -> loading
render user 3 -> error