Sub topic 1
Fetching JSON with the Fetch API
Prerequisites
Assume you know JavaScript promises and async/await, React components, JSX, props, and useState. You should also know that HTTP responses have status codes and that JSON is a text format commonly used for structured data.
Fetching JSON with the Fetch API
The Fetch API sends HTTP requests from the browser. fetch returns a promise that resolves to a Response object. It does not reject the promise for HTTP errors such as 404 or 500, so check response.ok yourself before reading the JSON body.
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();
}response.json() also returns a promise. The function above either returns the decoded JavaScript value or throws an error.
When to fetch: effects and dependencies
A React component should fetch after it renders when the request depends on component state or props. An effect is React code that runs after rendering to synchronize with something outside React, such as a network server.
The dependency array tells React when to run the effect again:
| Dependency array | Effect behavior |
|---|---|
| `[userId]` | Runs after the first render and when `userId` changes |
| `[]` | Runs after the first render only |
| No array | Runs after every render |
Include every changing value that the effect reads. If a user selects a different ID, [userId] ensures that the component requests the new user.
flowchart TD
A[Render with userId] --> B[Effect starts fetch]
B --> C{Response successful?}
C -->|Yes| D[Read JSON and update state]
C -->|No| E[Store error]
D --> F[Render user]
E --> G[Render error message]Fetching data inside useEffect
Keep the effect callback itself synchronous and define an inner asynchronous function. The cleanup function aborts a request when the component unmounts or before a new request starts.
import { useEffect, useState } from 'react';
function UserProfile({ userId }) {
const [state, setState] = useState({
status: 'loading',
data: null,
error: null,
});
useEffect(() => {
const controller = new AbortController();
async function loadUser() {
setState({ status: 'loading', data: null, error: null });
try {
const response = await fetch(`/api/users/${userId}`, {
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const data = await response.json();
setState({ status: 'success', data, error: null });
} catch (error) {
if (error.name === 'AbortError') return;
setState({ status: 'error', data: null, error });
}
}
loadUser();
return () => controller.abort();
}, [userId]);
if (state.status === 'loading') return <p>Loading...</p>;
if (state.status === 'error') return <p>{state.error.message}</p>;
return <h1>{state.data.name}</h1>;
}Modeling loading, error, and success
A request has distinct states. Rendering from an explicit status prevents the component from trying to display missing data or hiding a failed request.
The cleanup prevents an obsolete request from updating the component after its input changes. This avoids stale data appearing on screen.
Exercise
Why should the effect depend on userId instead of using an empty dependency array?
Show answer
The dependency tells React to fetch again when the selected user changes. An empty array would leave the component showing the first user's data.