Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 39 Β· Projects

Project: User Directory

Build a searchable, sortable user directory that loads JSON with fetch, shows loading and error states, retries, and opens a detail view. Every stage runs live.

A directory is the most common thing people build with AJAX: fetch a list from a server, show it, let the visitor narrow it down, and open one item for more detail. Contact lists, product catalogs, admin screens and job boards are all variations of the same page. If you can build this one well, you can build most data-driven screens.

We will build it in four stages, and every stage runs right here. The sandbox cannot call a real server, so a small function named mockFetch plays the part of the network: it waits a moment and then returns real Response objects with JSON bodies, just like fetch() would. In your own project you replace mockFetch with fetch and change nothing else. If any of the ideas below feel shaky, revisit your first fetch request, handling errors in fetch and rendering API data in the DOM.

The plan

Before writing code, decide what the data is and what the screen can show.

  • The API has two endpoints: GET /api/users returns an array of users, and GET /api/users/:id returns one user or a 404 with { "error": "..." }.
  • A user has an id, name, email, city, company and role.
  • The screen shows a search box, a sort menu, the list, and a detail panel.
  • Every request can be loading, successful, empty or failed, and the interface must say which.

The data flow we are building toward:

flowchart LR
  A["Page opens"] --> B["GET /api/users"]
  B -->|"200 + JSON"| C["Keep users in memory"]
  B -->|"network error or HTTP error"| E["Show error + Retry button"]
  E -->|"click Retry"| B
  C --> D["Filter by search, sort, render list"]
  D -->|"click a user"| F["GET /api/users/:id"]
  F --> G["Show detail panel"]

The list is fetched once; searching and sorting then work on the copy in memory, and only the detail view makes a second request.

Notice a design decision hiding in the diagram: search and sort do not call the server. With a few hundred users it is faster and simpler to download once and filter locally. With tens of thousands you would send the query to the server instead, which is what live search and pagination teaches.

Stage 1: fetch the list and show a status

Start with the smallest version that tells the truth: load the data, display it, and handle failure. The helper getJson is worth reading closely, because every later stage reuses it. fetch() only rejects when the network fails, so it must turn an HTTP error such as 404 or 500 into an exception itself.

Stage 1: load and display

Three habits in this small program carry the whole project:

  1. Build nodes with textContent. Names and cities come from a server, so they are untrusted. textContent can never turn data into markup, which makes script injection through a user's name impossible. See rendering API data and AJAX security.
  2. One status line for every state. The role="status" element is a polite live region, so screen readers announce "Loading users..." and then the result without moving focus.
  3. try/catch around the whole fetch-and-render step. A failure at any point ends up in one place that tells the user what happened.

Try changing '/api/users' to '/api/people' and run it again: you will see the 404 path.

Stage 2: search and sort as pure functions

Searching and sorting are derived data: the visible list is computed from the full list plus two settings (the query and the sort key). Put that logic in a pure function that takes inputs and returns a new array, with no DOM and no network. Then it is trivial to test, which is exactly what this console example does.

JS Stage 2: search and sort logic

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the output for the details that usually go wrong:

  • The query is trimmed and lowercased, so " NIMBUS " still matches.
  • localeCompare sorts text the way people expect, so "Γ‰mile" sorts with the Es, right after "Dalia", instead of after "Z" as a plain < comparison would put it.
  • filter() returns a new array, so sorting its result leaves the downloaded all untouched (the last log line proves it). If you ever sort without filtering first, sort a copy with [...all], because sort() reorders the array it is called on.
  • An empty result is an ordinary value ([]), not an error. The interface must handle it with its own message.

Stage 3: the complete directory

Now we combine everything. The program keeps the downloaded users in one variable, render() redraws the list from the current query and sort key, and a second request fetches one user for the detail panel. Two details deserve attention.

Retry. When loading fails, the status line shows a "Try again" button that calls loadUsers() again. Use the checkbox "Make the server fail" to see it: tick it, press Reload, then untick it and press "Try again".

Stale answers. Click user 1 and quickly user 2: two requests are in flight, and the first could finish last. Each call to showUser takes a ticket number, and a response is used only if its ticket is still the latest. Cancelling requests shows the same guard done with AbortController.

Stage 3: the user directory

Walk through what the program does when the page opens: loadUsers() clears the list, shows the loading text, awaits the JSON, stores it in users and calls render(). Typing in the search box or changing the sort menu calls render() directly, with no network traffic at all. Clicking a user calls showUser, which marks the selection, shows a loading line in the panel, and makes the second request.

Two small things make it feel finished. The status line distinguishes empty because nothing matched from empty because nothing loaded. And the selected button carries aria-current="true", so the selection is visible to assistive technology as well as in the styling.

Keep the downloaded array as the single source of truth and never edit it while searching or sorting. The visible list is always recomputed from it, so clearing the search box restores everything.

Moving to a real server

To use this against a real API, delete mockFetch and its data, and call the real fetch:

JavaScript
async function getJson(url) {
  const response = await fetch(url, { headers: { Accept: 'application/json' } });
  if (!response.ok) {
    const body = await response.json().catch(() => ({}));
    throw new Error(body.error || 'The server answered ' + response.status);
  }
  return response.json();
}

Everything else stays the same, which is the payoff of keeping the network in one small function. Remember that a page on another origin needs the server to send CORS headers (headers, auth and CORS).

Ideas to extend it

  1. Debounce the search so a fast typist does not re-render on every keystroke, or move searching to the server with a ?q= parameter (live search).
  2. Cache user details in a Map so reopening a user is instant (caching and polling).
  3. Add pagination or "load more" when the list grows.
  4. Validate the response before trusting it: check that users is an array of objects with the fields you display (validating JSON data).
  5. Remember the sort choice in the URL with history.replaceState so a page reload keeps it.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Why does getJson check response.ok and throw its own error?

    A 404 or 500 response is still a successful network exchange, so the fetch promise resolves. Checking response.ok lets the error reach the same catch block as network failures.
  2. 2. In the directory, why are the names added with textContent or append(string) instead of innerHTML?

    If a user's name contained markup, innerHTML would parse it and could run script. Text nodes treat the same characters as plain text.
  3. 3. What problem does the detailTicket counter solve?

    Responses can arrive in a different order than requests were sent. Comparing the ticket lets the program ignore any response that is no longer the latest.
  4. 4. Why is it reasonable for search and sort to work on the downloaded array instead of calling the server?

    With a few hundred records the whole list is small. Very large data sets need server-side search and pagination instead.

Summary

  • Model the screen as states (loading, success, empty, failed) and make each one visible.
  • Keep the network in one small function (getJson) that turns HTTP errors into exceptions and returns parsed JSON.
  • Treat search and sort as pure functions over the downloaded array, and sort a copy.
  • Build DOM nodes from data with textContent, and announce status with a role="status" live region.
  • Offer a Retry button on failure, and ignore stale responses with a ticket or an AbortController.
  • Swapping mockFetch for fetch is the only change needed to talk to a real server.

Next: Project: Weather Dashboard