Fetch API
js-fetch-api
Code Snippets
Cancellable fetch with AbortController
Every modern UI eventually needs to cancel in-flight requests: a search box that fires on every keystroke, a route change that abandons a partially loaded page, a tab close that should free sockets. `AbortController` is the standard primitive for this. This snippet covers the minimal abort pattern, a `fetchWithTimeout` helper that aborts on a deadline, and a hook-friendly cleanup pattern that pairs each request with its own controller.
React useFetch Hook with Cancellation
Building a useFetch from scratch teaches the pieces every data-fetching library has to solve: tracking loading and error state, cancelling in-flight requests when the URL changes, and ignoring stale responses after the component unmounts. This snippet covers the canonical AbortController-based hook, a generation-counter variant that protects against race conditions when AbortController is unavailable, and a mutate refetch helper for manual revalidation.
Fetch with Async/Await Recipes
The browser and Node 22+ both ship `fetch`, but the easy-to-miss details (`response.ok`, content-type parsing, body shape on POST, parallel error isolation) are exactly where bugs hide. This snippet collects four recipes built on `async`/`await` and a mocked `fetch` so each example runs end-to-end. Use it as the baseline for code that talks to JSON APIs without reaching for axios or a wrapper library.
Question Banks
Fetch API and Error Handling Quiz
Practice the small but easily-bungled `fetch` rituals: real error handling, Promise wrappers around timers, and `Promise.resolve` / `Promise.reject` for branching success states.
React Data Fetching and Effects Quiz
Four drills on fetching data with useEffect, avoiding stale closures, and cleaning up in-flight requests when the component unmounts or the input changes.
