Sub topic 1
Fetching JSON with the Fetch API
This chapter covers the browser's fetch function on its own, before React is involved. Every later chapter builds on it: effects, loading states, hooks, and query libraries all wrap the same request and response handling shown here.
Prerequisites
This chapter assumes you already know:
- JavaScript promises and
async/await, includingtry/catch. - Basic HTTP concepts: methods such as GET and PATCH, status codes, headers, and JSON.
- Enough React to read a component with props and
useState. No React code is needed until the last section.
What fetch does
fetch(url, options) starts an HTTP request and returns a promise. The promise resolves to a Response object as soon as the response headers arrive. The body has not necessarily been downloaded at that point.
Reading the body is a second asynchronous step. The Response object has methods for this, and each returns another promise:
| Method | Resolves to |
|---|---|
| `response.json()` | The body parsed as JSON |
| `response.text()` | The body as a string |
| `response.blob()` | The body as binary data |
A body can be read only once. Calling response.json() and then response.text() on the same response throws a TypeError. If you need both, call response.clone() first.
The basic pattern looks like this:
async function getUser(userId) {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
return data;
}This works when the server answers with a 200 status and valid JSON. The next section covers what happens when it doesn't.
The most common mistake: fetch does not reject on HTTP errors
A fetch promise rejects only when the request could not complete at all. Examples are a network failure, a DNS error, a blocked cross-origin request, or an aborted request. If the server answers with 404 or 500, the promise still resolves. From the network's point of view the request succeeded, because a response came back.
Consider this code:
async function getUserUnsafe(userId) {
const response = await fetch(`/api/users/${userId}`);
return response.json(); // runs even when the status is 404 or 500
}If the server returns a 404 with an HTML error page, response.json() throws a confusing SyntaxError about unexpected tokens. If it returns a 404 with a JSON body such as {"message":"Not found"}, the function returns that object as if it were a user. Neither outcome tells the caller that the request failed.
Check response.ok before reading the body. It is true when the status is in the 200 to 299 range.
async function getUser(userId) {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}Now the function rejects for both kinds of failure. Network problems reject inside fetch. HTTP error statuses reject through the throw. Callers handle both with one catch.
Reading error details from the body
Many APIs describe the problem in the response body. You can include that detail in the error. Read the body inside a try/catch, because an error response might not be JSON at all.
async function requestJson(url, options) {
const response = await fetch(url, options);
if (!response.ok) {
let detail = '';
try {
const body = await response.json();
detail = body.message ?? '';
} catch {
// The error response was not JSON. Fall back to the status alone.
}
const error = new Error(
detail || `Request failed with status ${response.status}`
);
error.status = response.status;
throw error;
}
return response.json();
}Attaching status to the error lets calling code react differently to a 401 (sign the user in) than to a 500 (show a retry button).
Some successful responses have no body. A 204 No Content reply to a DELETE request is the usual case, and response.json() would throw on it. Check for it before parsing:
if (response.status === 204) {
return null;
}
return response.json();Sending requests with options
The second argument to fetch is an options object. A plain GET needs none. Other methods need a few settings.
async function createUser(name) {
const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name }),
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}Three details matter here:
methoddefaults to'GET'. Set it explicitly for everything else.bodymust be a string,FormData, or another supported body type. Passing a plain object sends the text[object Object]. UseJSON.stringify.- Set
Content-Type: application/jsonyourself.fetchdoes not add it for string bodies, and many servers will not parse the body without it.
Build query strings with URLSearchParams rather than by concatenating strings. It encodes special characters for you.
const params = new URLSearchParams({ q: 'ada lovelace', page: 2 });
const response = await fetch(`/api/users?${params}`);The same applies to values placed in the URL path. If a value comes from user input, wrap it in encodeURIComponent(value) so characters such as / or ? cannot change the meaning of the URL.
Cancelling a request
A request can be cancelled by passing an AbortSignal in the options. You create the signal from an AbortController:
const controller = new AbortController();
fetch('/api/users', { signal: controller.signal })
.then((response) => response.json())
.catch((error) => {
if (error.name === 'AbortError') {
console.log('Request was cancelled');
return;
}
console.error(error);
});
controller.abort();Calling controller.abort() makes the pending promise reject with a DOMException named AbortError. This is a deliberate cancellation, not a failure, so code usually ignores it. A later chapter uses this to stop outdated requests in React components. For now, remember that cancellation arrives as a rejection and must be told apart from real errors by checking error.name.
Fetch in a React component
Putting a fetch call directly in a component body is wrong, even though it looks natural:
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
// Wrong: runs on every render
getUser(userId).then(setUser);
return <h1>{user?.name}</h1>;
}Calling setUser triggers a re-render. The re-render calls getUser again. That produces another response, another setUser, and an endless loop of requests. Rendering must stay free of side effects, and a network request is a side effect. React provides effects for this purpose. The next chapters cover when an effect runs, and then use the helper below inside one.
Here is the reusable helper you will carry forward. It checks the status, parses JSON, and accepts a signal:
export async function fetchJson(url, { signal } = {}) {
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}Common errors at a glance
| Symptom | Likely cause | Fix |
|---|---|---|
| `Unexpected token '<'` from `response.json()` | An HTML page, often a 404 or a dev-server fallback, was parsed as JSON | Check `response.ok` and the URL |
| Error handler never runs on a 500 | `fetch` resolves on HTTP errors | Throw when `!response.ok` |
| `body stream already read` | The body was consumed twice | Read once, or use `response.clone()` |
| Server receives an empty or malformed body | Missing `JSON.stringify` or `Content-Type` header | Stringify and set the header |
| `TypeError: Failed to fetch` | Network failure, or a CORS policy blocked the request | Check connectivity, the URL, and the server's CORS headers |
Exercise
A teammate writes const response = await fetch('/api/orders'); const orders = await response.json(); inside a try/catch and says errors are handled. The server returns status 500 with the JSON body {"message":"Database unavailable"}. What does the code do, and how do you fix it?
Show answer
The fetch promise resolves because a response arrived, and response.json() parses the error body successfully. The catch block never runs, and orders holds {"message":"Database unavailable"}, which the app may try to render as a list. Fix it by checking if (!response.ok) { throw new Error(Request failed with status ${response.status}); } after fetch and before response.json().
Exercise
You call fetch('/api/users', { method: 'POST', body: { name: 'Ada' } }). The server reports it received the text [object Object]. What two changes make the request correct?
Show answer
Convert the body with JSON.stringify({ name: 'Ada' }), and add the header 'Content-Type': 'application/json' so the server knows to parse it as JSON.