8. Fetch, HTTP & error UX
JavaScript · 56 pages source format
fetch(url) returns a Promise resolving to Response. Check response.ok — fetch does not reject on 404. Parse JSON with .json(). Build loading, success, and error UI states. Same patterns apply in Node with fetch (built-in since v18).
What you'll learn
- fetch API
- HTTP status codes
- Loading/error UI states
- Headers & POST bodies
- AbortController
GET request
const res = await fetch(url). if (!res.ok) throw new Error(res.status). const data = await res.json().
async function getPost(id) {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
}Do this now
Fetch https://jsonplaceholder.typicode.com/posts/1 and log title.
POST with JSON
fetch(url, { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(data) }).
Do this now
Create a new post via POST. Log the returned id.
Three UI states
Every async UI needs: loading (spinner/skeleton), success (data rendered), error (message + retry). Model as state object or simple flags.
- idle — before fetch
- loading — fetch in flight
- success — data rendered
- error — message shown, retry available
Do this now
Add a "Load posts" button to a page. Show loading text, then list titles, or error with retry button.
AbortController
Cancel in-flight fetch when user navigates away or types a new search. Pass signal in fetch options.
const controller = new AbortController()
fetch(url, { signal: controller.signal })
// later: controller.abort()Do this now
Add search that aborts previous fetch when user types again.
Error messages for humans
Log technical details to console. Show friendly messages to users. Distinguish network errors from 404/500.
Do this now
Write getErrorMessage(err) returning user-friendly strings for common failure modes.