Stage 2 · Lesson 9 of 10
Fetching data and handling every state
The is the browser's built in way to call a server. fetch(url) returns a for a response, and await res.json() reads the body as data. One detail catches everyone.
fetch only rejects when the network fails, so a 404 or 500 still resolves, and you must check res.ok yourself. Sending data means setting a method, a Content-Type header and a body made with JSON.stringify. A real UI has four states for every request: loading, success, empty and error, and each needs something on screen.
Use AbortController to cancel a request when the user types again or leaves the page. Otherwise an old, slow response can overwrite a newer one. By default, fetch sends your only to your own site.
Calls to another are subject to , a browser rule that the server, not your code, has to relax.
A question to check yourself, an AI practice session and 3 cheat sheet entries come with the full roadmap. Unlock
Resources for this stage
Start with· follow one of these
- CoursePaidGrokking JavaScript Fundamentals
Design Gurus · Beginner · $50
Guided beginner course on the language core, with quizzes after every chapter
- GuideFreeJavaScript.info
Ilya Kantor
Free and thorough: Part 1 for the language, Part 2 for the DOM and events, Part 3 for fetch
Practise
Keep handy
Also worth your time
- You Don't Know JS YetGo deeper
For when scope, this, coercion or async behaviour still feel like magic