LEARN. PRACTICE. EXPLAIN.
Learning paths & interview practiceP
Frontend foundations
LESSON 4 OF 4 · ABOUT 15 MINUTES + EXERCISE

How do you fetch data without misleading the user?

THE IDEA

What it is

Fetching data is an asynchronous operation with several possible states: loading, success with data, success with no data, and failure. A network response also has an HTTP status; receiving a response does not necessarily mean the request succeeded.

Why you need it

An empty screen can mean no records or a broken service. Distinguishing states helps the user decide whether to retry, correct input, or wait.

How it works

  1. Start loading while preserving useful existing content where appropriate.
  2. Send the request and check its status.
  3. Validate the response shape before using it.
  4. Render success, empty, or error; ignore results that no longer belong to the current view.
JavaScript

An API helper for your own /api/items endpoint

async function loadItems(signal) {
  const response = await fetch("/api/items", { signal });
  if (!response.ok) throw new Error(`Request failed: ${response.status}`);
  const data = await response.json();
  if (!Array.isArray(data.items)) throw new Error("Unexpected response");
  return data.items;
}

This helper requires an endpoint returning an items array. The calling component must handle loading, errors, cancellation, and rendering. Abort an obsolete request or guard its result when newer searches replace it.

Good practices and why

  • Check response status and validate the fields your UI depends on.
  • Preserve user input on failure and make retries act on the intended request.

Common mistakes

  • Treating every caught error as an empty result.
  • Letting an older search response overwrite a newer one.
GUIDED IMPLEMENTATION

Try it yourself

Mock successful, empty, failed, and delayed responses for an items screen. Change the query while a request is pending.

What a successful result looks like

Every outcome has a distinct UI and an obsolete response cannot replace the current results.

0 / 6000 characters · Saved on this device. Do not include passwords or private data.

Check your understanding

Does fetch automatically reject its promise for an HTTP 500 response?

Answer the understanding check correctly to record exercise completion.

PUT THE IDEA UNDER PRESSURE

Related interview practice

These scenarios add constraints and follow-up questions to the concepts you just learned.

Further reading

Selected primary references · reviewed 2026-10-09. Examples are educational; use your framework’s documented integration guidance when building a deployed system.

AlifBay Prep