Build a task list that loads JSON when you press a button, reports HTTP errors, and displays useful feedback while the request is running. This example uses a local data file so you can learn the request flow without an API account, secret key, or unreliable demo service.
The three files below are enough to run the example: an HTML page, a JavaScript module, and a JSON dataset. The error checks cover a missing file, bad JSON, and data that does not match the task format.
Level: beginner with basic JavaScript. Tools: a modern browser and a local static server. No framework, database, package installation, or API credentials. The example uses AbortSignal.timeout(); older browsers need a compatible cancellation approach.
Table of Contents
What Fetch actually does
A request asks a server for a resource. The response has a status, headers, and a body. Fetch returns a promise for that response; parsing its JSON body is a separate asynchronous step. A server can return a response with status 404 or 500 without Fetch rejecting its promise. That is why checking response.ok belongs before parsing and rendering.
1. Create a small local project
Make a folder named fetch-task-list. Save the following page as index.html. The status paragraph uses role="status" so updates are available to assistive technology. The button remains a real button that works with a keyboard.
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>A small Fetch API task list</title>
<style>body{font:18px/1.7 system-ui;max-width:44rem;margin:3rem auto;padding:0 1rem;color:#182f2b}button{font:inherit;padding:.6rem 1rem;background:#126858;color:white;border:0;border-radius:6px}button:focus-visible{outline:3px solid #a04715;outline-offset:4px}</style>
<h1>My learning tasks</h1>
<button id="load-tasks" type="button">Load tasks</button>
<p id="status" role="status">Ready when you are.</p>
<ul id="tasks"></ul>
<script type="module" src="./app.js"></script>
</html>
Save the following data as tasks.json in the same folder. JSON requires double quotes around property names and string values. There is no trailing comma after the final item.
[
{"id": 1, "title": "Read the Fetch API example", "done": true},
{"id": 2, "title": "Handle a missing JSON file", "done": false},
{"id": 3, "title": "Add a completed-task filter", "done": false}
]
2. Load, validate, and display the tasks
Save this module as app.js. The first function only retrieves and checks data. Keeping it separate from the page makes it easier to test failures without clicking through the interface. Its optional second argument lets a test supply a controlled response instead of contacting a server.
export async function getTasks(url, fetchImpl = fetch) {
const response = await fetchImpl(url, {
headers: { Accept: 'application/json' },
signal: AbortSignal.timeout(8000),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const tasks = await response.json();
if (!Array.isArray(tasks) || !tasks.every(task =>
task && Number.isInteger(task.id) && typeof task.title === 'string'
&& typeof task.done === 'boolean')) {
throw new Error('The server returned an unexpected task format.');
}
return tasks;
}
if (typeof document !== 'undefined') {
const button = document.querySelector('#load-tasks');
const status = document.querySelector('#status');
const list = document.querySelector('#tasks');
button.addEventListener('click', async () => {
button.disabled = true;
status.textContent = 'Loading tasks…';
list.replaceChildren();
try {
const tasks = await getTasks('./tasks.json');
for (const task of tasks) {
const item = document.createElement('li');
item.textContent = `${task.done ? 'Done' : 'To do'}: ${task.title}`;
list.append(item);
}
status.textContent = tasks.length ? `${tasks.length} tasks loaded.` : 'No tasks yet.';
} catch (error) {
status.textContent = error.name === 'TimeoutError'
? 'The request timed out. Please try again.'
: `Could not load tasks: ${error.message}`;
} finally {
button.disabled = false;
}
});
}
3. Run the page through a local server
Open a terminal in the project folder. If Python 3 is installed, run python3 -m http.server 8000 --bind 127.0.0.1, then visit http://127.0.0.1:8000. On Windows, your Python command may be py. Keep the terminal open while using the page and stop it with Ctrl+C when finished.
Opening the HTML file directly from a file manager gives it a file: URL. Browser security rules can then prevent the JSON request. A local server gives the page and JSON file the same HTTP origin and makes the exercise behave like a small website.
Expected result
Press Load tasks. The button is temporarily disabled, the old list is cleared, and the page reports 3 tasks loaded. The list contains one completed task and two tasks still to do. Pressing the button again replaces the list rather than appending duplicates.
The order matters. Clear the old result before a new request, validate the response, create the list items, then announce success. The finally block restores the button after both successful and unsuccessful requests, so an error cannot leave the interface stuck.
Why the example uses these checks
- Use textContent for data: a task title is text, not trusted HTML. A title containing markup should appear literally instead of becoming an executable element.
- Check the data shape: valid JSON is not necessarily a valid task list. This example requires an array, integer IDs, string titles, and boolean completion values.
- Bound the waiting time: the request has an eight-second timeout. A real product should choose its timeout around its actual server behavior and explain how users can retry.
- Prevent competing clicks: disabling the button keeps this simple example from starting overlapping requests. A live search box needs a different design, such as cancelling the previous request.
Try the failure cases yourself
| Change | Expected behavior |
|---|---|
| Rename tasks.json | An HTTP 404 error appears; the button becomes usable again. |
| Replace the data with [] | The page says “No tasks yet.” |
| Set done to a quoted string | The format validation rejects the response. |
| Remove a closing JSON bracket | The parsing error is caught and displayed. |
| Put <b>hello</b> in a title | The literal markup appears as text. |
| Use browser network throttling | The loading state remains visible; a sufficiently slow request times out. |
Common problems and their fixes
“Unexpected token <”: the URL may be returning an HTML error page rather than JSON. Check the Network panel, request URL, status, and response body. Do not solve this by hiding the parsing error.
“Failed to fetch”: check that the local server is running and that the URL is correct. When switching to another website’s API, its server must allow your origin through CORS. Setting mode: 'no-cors' does not give JavaScript readable JSON.
The button does nothing: check that app.js is in the same folder and the script has type="module". Read the browser console for a missing file or syntax error. Modern browser support is required for the timeout helper used here.
Add a completed-task filter
Add a checkbox that filters completed tasks after the request finishes. Keep the full array in memory and derive the visible list from it. Then add a task count and an empty-state message for the filtered result. This keeps network access separate from presentation and gives you a concrete reason to practice array filtering.
This lesson reads a static file. A production API also needs authentication decisions, authorization on the server, rate limits, request validation, and a plan for private data. Never put a private service key in browser JavaScript.
Download the complete example ZIP
The ZIP contains the original example files, a README, and an MIT license. No account or paid dependency is required for these examples.
References and verification
MDN: Using the Fetch API explains request and response behavior. This guide was rewritten with AI assistance on October 19, 2026. Automated checks exercised successful responses, HTTP errors, malformed data, rejected requests, and timeout-signal setup. The browser page was also checked during the site audit.
