Frontend development · Beginner · 22 min
Fetch JSON from an API and show it with loading and error states
By Padding · Updated 18 Nov 2026
Node.js 26.13 LTS (node:26 image) · Fetch Standard and DOM AbortSignal · checked in Chromium with Playwright 1.65.1
You will build a market price search that loads JSON with fetch, shows loading, empty, error and success states, gives up after five seconds and never shows results out of order.
On this page
Most pages that show data from an API are written for the happy path: call fetch, put the result on screen. Then the network is slow and the page sits blank, the server returns a 500 and the page shows nothing at all, or the user types a second search and the answer to the first one lands on top of it. Each of those is a state the page has to handle on purpose.
In this tutorial you build a small market price search. A Node script with no dependencies plays the part of the API and serves a list of twelve sample food prices as JSON. The page loads the list, lets people search it, and has a clear message for every state: loading, empty, error and success. You add a five-second timeout with AbortSignal.timeout() and cancel a search that has been replaced by a newer one, so results never arrive out of order. A short Playwright script checks every state in a real browser at the end.
The timeout and the cancelling matter most on slow and expensive connections, such as a low-end Android phone on prepaid mobile data. A request that will never finish should end with a message and a Try again button, not a page that loads forever, and a search nobody is waiting for any more should stop downloading.
Step 1 · Start a small JSON API
Make a demo folder and write the server. It answers /api/prices?q=<search> with the matching prices as JSON and serves the page's files from the same folder, so the page and the API share an address and you need no CORS settings.
mkdir -p ~/price-search-demo
cd ~/price-search-demo
cat > server.mjs <<'JS'
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
const PORT = 8471;
// Sample prices for the demo, per kg unless the unit says otherwise.
const prices = [
{ item: 'Tomatoes', unit: 'kg', price: 1200 },
{ item: 'Onions', unit: 'kg', price: 900 },
{ item: 'Maize', unit: 'kg', price: 650 },
{ item: 'Rice', unit: 'kg', price: 1500 },
{ item: 'Yam', unit: 'kg', price: 800 },
{ item: 'Plantain', unit: 'kg', price: 700 },
{ item: 'Garri', unit: 'kg', price: 1100 },
{ item: 'Beans', unit: 'kg', price: 1800 },
{ item: 'Palm oil', unit: 'litre', price: 2500 },
{ item: 'Tilapia', unit: 'kg', price: 3200 },
{ item: 'Cassava', unit: 'kg', price: 400 },
{ item: 'Groundnuts', unit: 'kg', price: 2100 },
];
const files = {
'/': ['index.html', 'text/html; charset=utf-8'],
'/app.js': ['app.js', 'text/javascript; charset=utf-8'],
'/api.js': ['api.js', 'text/javascript; charset=utf-8'],
'/view.js': ['view.js', 'text/javascript; charset=utf-8'],
};
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function send(res, status, type, body) {
if (res.destroyed) return; // the browser has already given up on this request
res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' });
res.end(body);
}
function sendJson(res, status, data) {
send(res, status, 'application/json; charset=utf-8', JSON.stringify(data));
}
createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost');
if (url.pathname === '/api/prices') {
const q = (url.searchParams.get('q') ?? '').trim().toLowerCase();
// Two searches that misbehave on purpose, so the page's error handling can be tried.
if (q === 'fail') return sendJson(res, 500, { error: 'Price list unavailable' });
if (q === 'hang') {
await wait(15000);
return sendJson(res, 200, []);
}
// One-letter searches answer slowly, which makes out-of-order replies easy to see.
await wait(q.length === 1 ? 1500 : 300);
return sendJson(res, 200, prices.filter((p) => p.item.toLowerCase().includes(q)));
}
if (url.pathname.startsWith('/api/')) return sendJson(res, 404, { error: 'Not found' });
const file = files[url.pathname];
if (!file) return send(res, 404, 'text/plain; charset=utf-8', 'Not found');
try {
send(res, 200, file[1], await readFile(new URL(file[0], import.meta.url)));
} catch {
send(res, 404, 'text/plain; charset=utf-8', `${file[0]} does not exist yet`);
}
}).listen(PORT, () => console.log(`Price API listening on http://localhost:${PORT}`));
JSThe server has three behaviours worth knowing before you write the page:
- An empty search returns all twelve prices after 300 milliseconds. A one-letter search, such as
t, takes 1.5 seconds. - Searching for
failreturns HTTP 500 with a JSON error body. - Searching for
hangwaits 15 seconds before answering, longer than the page will wait.
Start it in its own terminal window and leave it running for the rest of the tutorial. It reads the page's files from disk on every request, so you never need to restart it after editing them.
cd ~/price-search-demo
node server.mjsCheck it worked
The terminal prints Price API listening on http://localhost:8471. In a second terminal, ask for a search and for the failing one:
curl -s 'http://localhost:8471/api/prices?q=to'
echo
curl -s -o /dev/null -w '%{http_code}\n' 'http://localhost:8471/api/prices?q=fail'The first command prints [{"item":"Tomatoes","unit":"kg","price":1200}] and the second prints 500.
Step 2 · Load the prices with fetch
Write the page. It has a search box, a message area and an empty list. The search box does nothing yet; you wire it up in a later step.
cd ~/price-search-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Market prices</title>
<style>
* { box-sizing: border-box; }
body { margin: 0; background: #f6f7f8; color: #1b1f24; font-family: system-ui, sans-serif; line-height: 1.5; }
main { max-width: 32rem; margin: 0 auto; padding: 1rem; }
label { display: block; font-weight: 600; margin-bottom: 0.25rem; }
input { width: 100%; min-height: 3rem; padding: 0.5rem 0.75rem; font: inherit; border: 1px solid #7d8592; border-radius: 0.5rem; }
#message { min-height: 3rem; margin: 0.75rem 0; color: #5a6270; }
#message button { min-height: 2.75rem; margin-left: 0.25rem; padding: 0 1rem; font: inherit; }
#prices { list-style: none; margin: 0; padding: 0; }
#prices li { display: flex; justify-content: space-between; gap: 1rem; padding: 0.75rem 0; border-bottom: 1px solid #d5d9df; }
#prices[aria-busy="true"] { opacity: 0.5; }
</style>
<script type="module" src="app.js"></script>
</head>
<body>
<main>
<h1>Market prices</h1>
<label for="search">Search for an item</label>
<input id="search" type="search" autocomplete="off">
<div id="message" role="status"></div>
<ul id="prices" aria-label="Prices"></ul>
</main>
</body>
</html>
HTMLNow the function that talks to the API. Keep it in its own module, api.js, so the rest of the page never deals with URLs or status codes:
cd ~/price-search-demo
cat > api.js <<'JS'
export async function fetchPrices(query = '') {
const response = await fetch(`/api/prices?q=${encodeURIComponent(query)}`);
if (!response.ok) {
throw new Error(`The price list is not available right now (error ${response.status}). Try again in a moment.`);
}
return response.json();
}
JSThe response.ok check is the line most often left out. fetch only rejects when it gets no response at all, for example when the network is down. A 404 or a 500 is still a response, so the promise resolves as normal and, without this check, the page would try to show the server's error body as if it were prices. response.ok is true for status codes 200 to 299 and false for everything else. encodeURIComponent keeps a search with spaces or symbols, such as palm oil, from breaking the URL.
Then a first app.js that loads every price and lists it:
cd ~/price-search-demo
cat > app.js <<'JS'
import { fetchPrices } from './api.js';
const list = document.querySelector('#prices');
const prices = await fetchPrices();
list.replaceChildren(...prices.map((p) => {
const li = document.createElement('li');
li.textContent = `${p.item}: ${p.price.toLocaleString('en')} per ${p.unit}`;
return li;
}));
JSThe text goes in with textContent, never innerHTML, so a price name containing <script> would show as plain text instead of running.
Check it worked
Open http://localhost:8471/ in your browser. After a moment you see a list of twelve prices, starting with Tomatoes: 1,200 per kg. Open the browser's developer tools, go to the Console and run:
fetch('/api/nope').then((r) => console.log(r.ok, r.status))It logs false 404: the promise resolved, even though the request failed. That is why fetchPrices checks response.ok itself.
Step 3 · Show loading, empty and error states
Right now the page is blank while it waits, and if the request fails it stays blank for good. Give every state its own message. The rendering goes in view.js, so there is one place that decides what each state looks like:
cd ~/price-search-demo
cat > view.js <<'JS'
const message = document.querySelector('#message');
const list = document.querySelector('#prices');
function priceItem(p) {
const li = document.createElement('li');
const name = document.createElement('span');
const price = document.createElement('span');
name.textContent = p.item;
price.textContent = `${p.price.toLocaleString('en')} per ${p.unit}`;
li.append(name, price);
return li;
}
export function showLoading() {
list.setAttribute('aria-busy', 'true');
message.textContent = 'Loading prices…';
}
export function showPrices(prices, query) {
list.removeAttribute('aria-busy');
list.replaceChildren(...prices.map(priceItem));
if (prices.length > 0) {
message.textContent = `${prices.length} ${prices.length === 1 ? 'price' : 'prices'}`;
} else if (query) {
message.textContent = `No prices match "${query}". Check the spelling or try a shorter word.`;
} else {
message.textContent = 'No prices have been added yet.';
}
}
export function showError(error, retry) {
list.removeAttribute('aria-busy');
list.replaceChildren();
const text = document.createElement('span');
text.textContent = error.message;
const button = document.createElement('button');
button.type = 'button';
button.textContent = 'Try again';
button.addEventListener('click', retry);
message.replaceChildren(text, button);
}
JSA few decisions in there:
- Loading keeps the old list, dimmed.
aria-busy="true"tells assistive technology the list is being updated, and the CSS you wrote earlier dims it. Keeping the old results stops the page jumping on every keystroke once search is wired up. - Empty is not the same as an error. A search with no matches says so and suggests what to do next. A failure clears the list, so nobody mistakes old prices for current ones, and offers a Try again button instead of retrying on its own, which would quietly use data on a metered connection.
- One live region. The message area has
role="status", so screen readers announce each new message (loading, the count, no matches, the error) politely, without interrupting what they are reading.
Replace app.js so it uses these. It also reads ?q= from the page address, which lets you open each state directly:
cd ~/price-search-demo
cat > app.js <<'JS'
import { fetchPrices } from './api.js';
import { showLoading, showPrices, showError } from './view.js';
async function load(query) {
showLoading();
try {
const prices = await fetchPrices(query);
showPrices(prices, query);
} catch (error) {
showError(error, () => load(query));
}
}
load(new URLSearchParams(location.search).get('q') ?? '');
JSCheck it worked
Reload http://localhost:8471/: the message reads 12 prices above the list. Then try each state by its address:
http://localhost:8471/?q=tshowsLoading prices…for about a second and a half, then4 prices.http://localhost:8471/?q=zzzshowsNo prices match "zzz". Check the spelling or try a shorter word.and an empty list.http://localhost:8471/?q=failshowsThe price list is not available right now (error 500). Try again in a moment.with a Try again button. Clicking it showsLoading prices…briefly and then the same error, because the server fails every time.
Step 4 · Stop waiting after five seconds
Open http://localhost:8471/?q=hang. The page says Loading prices… for 15 seconds. On a real connection that drops packets, a request can hang far longer than that, and fetch has no time limit of its own. Add one.
AbortSignal.timeout(5000) gives you a signal that aborts itself after five seconds. Pass it to fetch and the request is cancelled at that point, with an error named TimeoutError. The function also takes an optional signal from the caller, for the cancelling you add next, and AbortSignal.any() combines the two: whichever fires first wins.
Replace api.js:
cd ~/price-search-demo
cat > api.js <<'JS'
const TIMEOUT_MS = 5000;
// Turn low-level failures into messages a person can act on.
function explain(error) {
if (error.name === 'AbortError') return error; // cancelled on purpose by the caller
if (error.name === 'TimeoutError') {
return new Error('The price list took too long to load. Check your connection and try again.');
}
if (error.name === 'SyntaxError') {
return new Error('The price list came back in a form this page cannot read.');
}
return new Error('Could not reach the price list. Check your connection and try again.');
}
export async function fetchPrices(query = '', signal) {
const signals = [AbortSignal.timeout(TIMEOUT_MS)];
if (signal) signals.push(signal);
let response;
let data;
try {
response = await fetch(`/api/prices?q=${encodeURIComponent(query)}`, {
signal: AbortSignal.any(signals),
});
if (response.ok) data = await response.json();
} catch (error) {
throw explain(error);
}
if (!response.ok) {
throw new Error(`The price list is not available right now (error ${response.status}). Try again in a moment.`);
}
return data;
}
JSReading the body with response.json() sits inside the same try, because the timeout covers the download of the body as well as the wait for headers. A large response on a slow line can time out halfway through. The SyntaxError case covers a server that answers 200 with something that is not JSON, such as an HTML error page from a proxy.
Five seconds suits this small list. Pick your own limit from how long your API takes on a slow connection, and keep the message honest: it says the request took too long, not that the data does not exist.
Check it worked
Open http://localhost:8471/?q=hang again. After about five seconds the message changes to The price list took too long to load. Check your connection and try again. with a Try again button. In the developer tools Network panel, the prices?q=hang request is marked as cancelled or failed rather than still pending.
Step 5 · Cancel stale searches as the user types
Now wire up the search box. The obvious version runs a search on every input event, and it has a bug: the server answers one-letter searches slowly, so if you type t and then o, the reply for to arrives first and the reply for t arrives about a second later and replaces it. The page ends up showing four prices under a box that says to. Real APIs do this too, whenever an earlier query happens to be slower.
The fix is to cancel the previous request when a new search starts. Each search gets its own AbortController; starting a new search calls abort() on the last one. The cancelled fetch rejects with an AbortError, which api.js passes through unchanged and app.js ignores, because a newer search already owns the screen.
Replace app.js:
cd ~/price-search-demo
cat > app.js <<'JS'
import { fetchPrices } from './api.js';
import { showLoading, showPrices, showError } from './view.js';
const input = document.querySelector('#search');
let controller;
async function search(query) {
controller?.abort(); // the previous search is out of date
controller = new AbortController();
const { signal } = controller;
showLoading();
try {
const prices = await fetchPrices(query, signal);
if (signal.aborted) return;
showPrices(prices, query);
} catch (error) {
if (error.name === 'AbortError') return; // a newer search replaced this one
showError(error, () => search(query));
}
}
input.addEventListener('input', () => search(input.value.trim()));
input.value = new URLSearchParams(location.search).get('q') ?? '';
search(input.value.trim());
JSThe if (signal.aborted) return; line is a second guard. It covers the moment where a reply has already arrived but the code after await has not run yet; whatever happens, only the latest search writes to the page. Aborting also stops the browser downloading the rest of an old reply, which saves data as well as confusion.
Many search boxes also wait for a pause in typing, often around 300 milliseconds, before sending a request. That cuts the number of requests, but it does not replace cancelling: a slow reply to an earlier pause can still arrive after a later one.
Check it worked
Reload http://localhost:8471/ and type to into the search box at normal speed. The message shows Loading prices…, then 1 price, and the list shows only Tomatoes. Wait two more seconds: it stays that way. In the Network panel, the prices?q=t request is marked as cancelled. Type fail to see the error with its button, then clear the box to get all twelve prices back.
Step 6 · Check every state in a browser with Playwright
Clicking through by hand catches problems once. A script catches them every time the code changes. Install Playwright into the demo folder; --with-deps also installs the system libraries Chromium needs on Linux, which can ask for your password:
cd ~/price-search-demo
npm init -y > /dev/null
npm install playwright@1.65.1
npx playwright install --with-deps chromiumWrite a test that types into the search box like a person and checks what appears in the message area and the list:
cd ~/price-search-demo
cat > test-states.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 390, height: 844 } });
const search = page.getByLabel('Search for an item');
const message = page.getByRole('status');
const items = page.locator('#prices li');
const until = (text, timeout = 5000) => page.locator('#message', { hasText: text }).waitFor({ timeout });
const cancelled = [];
page.on('requestfailed', (request) => cancelled.push(request.url()));
// Success: all twelve prices.
await page.goto('http://localhost:8471/');
await until(/^12 prices$/);
assert.equal(await items.count(), 12);
assert.equal(await items.first().textContent(), 'Tomatoes1,200 per kg');
// fetch resolves on a 404; only response.ok tells you it failed.
const notFound = await page.evaluate(async () => {
const r = await fetch('/api/nope');
return [r.ok, r.status];
});
assert.deepEqual(notFound, [false, 404]);
// Loading, then a newer search replaces a slower one.
await search.fill('t');
await until('Loading prices');
assert.equal(await page.locator('#prices').getAttribute('aria-busy'), 'true');
await search.fill('to');
await until(/^1 price$/);
await page.waitForTimeout(2000); // longer than the slow reply to "t"
assert.equal(await message.textContent(), '1 price', 'the reply to "t" never shows');
assert.deepEqual(await items.allTextContents(), ['Tomatoes1,200 per kg']);
assert.ok(cancelled.some((url) => url.endsWith('?q=t')), 'the stale request was cancelled');
// Empty.
await search.fill('zzz');
await until('No prices match "zzz"');
assert.equal(await items.count(), 0);
// Server error, with a working Try again button.
await search.fill('fail');
await until('error 500');
assert.equal(await items.count(), 0);
const failRequests = [];
page.on('request', (request) => { if (request.url().endsWith('?q=fail')) failRequests.push(request); });
await page.getByRole('button', { name: 'Try again' }).click();
await until('error 500');
assert.equal(failRequests.length, 1, 'Try again sends a new request');
// Timeout after five seconds instead of waiting 15.
const started = Date.now();
await search.fill('hang');
await until('took too long', 8000);
const waited = Date.now() - started;
assert.ok(waited >= 4500 && waited < 8000, `timed out after ${waited} ms`);
// Recovery: a normal search works again.
await search.fill('rice');
await until(/^1 price$/);
assert.deepEqual(await items.allTextContents(), ['Rice1,500 per kg']);
// No sideways scrolling on a phone-sized screen.
const overflow = await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth);
assert.equal(overflow, false);
await browser.close();
console.log('PASS: loading, empty, error, timeout and stale searches all handled');
JS
node test-states.mjsThe list items read Tomatoes1,200 per kg in the test because textContent joins the two spans with no space; on screen, flexbox places the name on the left and the price on the right. The test takes around ten seconds, most of it the deliberate timeout.
Check it worked
The last line of output is PASS: loading, empty, error, timeout and stale searches all handled. To see the test catch the out-of-order bug, delete the line controller?.abort(); // the previous search is out of date from app.js and run node test-states.mjs again: it stops with an AssertionError about the reply to "t". Put the line back and it passes.
Step 7 · Stop the server and clean up
Go back to the terminal running the server and press Ctrl+C. Then remove the demo folder, which also removes the local Playwright install. The browser Playwright downloaded stays in its shared cache; npx playwright uninstall removes that too if you no longer need it.
cd ~
rm -rf ~/price-search-demoCheck it worked
curl -s http://localhost:8471/api/prices prints nothing and exits with an error, because nothing is listening, and ls ~/price-search-demo reports that there is no such file or directory.
Next steps
- Learn how promises,
asyncandawaitbehave outside the browser in wait for slow work with promises and async/await. - Decide when a spinner, a skeleton or a progress bar suits the wait in design loading states: spinners, skeletons and progress.
- Write better no-results messages with design empty states that say what to do next.
- Replace the dimmed list with a placeholder layout in build skeleton loading screens in CSS.
Part of these paths
Related tutorials
- Wait for slow work in JavaScript with promises and async/awaitYou will see why JavaScript code seems to run out of order, wrap a timer in a promise, rewrite it with async/await and try/catch, time three requests one after another against all at once, and finish with a script that loads files in parallel and reports any that failed.
- Design loading states: spinners, skeletons and progressYou will have a loading-state table for every wait in a booking flow, with the pattern chosen by expected wait time, and Figma frames for a skeleton, a button spinner, an upload progress bar, an optimistic switch and a "taking longer than usual" state.
- Design empty states that say what to do nextYou will have four empty-state frames for one list screen, first use, no results, all done and cleared, each with its own message and next action, plus a copy table a developer can build from.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials