Fetch API
Fetch API covers GET and POST JSON requests, response.ok checks, AbortController cancellation, response body parsing, and async bugs.
Course: React — Routing & API Integration Lesson: 08
Learning objectives
Use the browser Fetch API for GET and POST requests, parse JSON safely, handle HTTP failures, cancel requests, and avoid common asynchronous bugs.
Basic GET request
fetch() returns a Promise that resolves to a Response. An HTTP error status such as 404 does not normally reject the Promise; inspect response.ok or response.status.
async function getProducts() {const response = await fetch("/api/products");if (!response.ok) {throw new Error(`Request failed with status ${response.status}`);}return response.json();}
POST JSON data
async function createProduct(product) {const response = await fetch("/api/products", {method: "POST",headers: {"Content-Type": "application/json","Accept": "application/json"},body: JSON.stringify(product)});if (!response.ok) {const message = await response.text();throw new Error(message || "Unable to create product");}if (response.status === 204) return null;return response.json();}
JSON.stringify converts a JavaScript value into a JSON request body. The Content-Type header tells the server how to interpret it.
Use Fetch inside an Effect carefully
useEffect(() => {const controller = new AbortController();async function load() {try {setStatus("loading");const response = await fetch("/api/products", {signal: controller.signal});if (!response.ok) throw new Error("Could not load products");setProducts(await response.json());setStatus("success");} catch (error) {if (error.name !== "AbortError") {setError(error);setStatus("error");}}}load();return () => controller.abort();}, []);
An AbortController helps stop a request when the component no longer needs its result. For changing identifiers or search terms, include the relevant dependency and cancel the previous request during cleanup.
Handle response bodies once
A response body is a stream and should generally be consumed once. Choose json(), text(), blob(), or another parser according to the endpoint contract. Do not call response.json() and then expect to read the same body again as text.
Error categories
Distinguish network errors, HTTP errors, parsing errors, cancellation, and application-level validation errors. These have different causes and may require different user messages or retry behavior.
Common mistakes
- Not checking
response.ok. - Calling
response.json()for a 204 response. - Forgetting
JSON.stringifyfor JSON request bodies. - Treating an aborted request as a user-visible failure.
- Updating state from a request that is no longer relevant.
- Logging sensitive request headers or payloads.
Best practices
Wrap repeated request behavior in service functions, use AbortController, validate response data, and expose clear loading/error/success states. For complex caching and synchronization, evaluate a dedicated server-state library rather than rebuilding all behavior manually.
Interview questions & answers
Interview preparation
5 questions grouped by difficulty — expand any card for a model answer and follow-up probe.
Beginner
1What does fetch return?
BeginnerModel answer
A Promise that resolves to aResponseobject describing status, headers, and a readable body stream.2What is AbortController?
BeginnerModel answer
A browser API that lets you abort an in-flight fetch viasignal, typically in Effect cleanup when the request is no longer needed.
Intermediate
3Why does a 404 not automatically reject a Fetch Promise?
IntermediateModel answer
Fetch only rejects for network failures. HTTP error statuses still resolve, so application code must inspectresponse.ok.4How should a 204 response be handled?
IntermediateModel answer
Treat success with no body—do not callresponse.json(); returnnullor skip parsing.
Advanced
5How do you send JSON in a POST request?
AdvancedModel answer
Setmethod: "POST",Content-Type: application/json, andbody: JSON.stringify(payload), then check the response.
Practice
Build a product search request with a query parameter. Cancel the previous request when the user changes the search term and display loading, empty, error, and result states.