Sending and Getting Data via HTTP
Sending and getting data via HTTP in a routed React app means loading data from a backend API when a page opens, and posting form data to the API when the user submits, then moving to another route afterwards. The browser's built-in fetch function handles the requests, useEffect triggers loading at the right time, and React Router's hooks connect the data to the current URL.
Loading data for the current route
A detail page usually reads an id from the URL with useParams and fetches that item. The effect re-runs whenever the id changes, so moving from one product to the next loads fresh data.
import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
function ProductPage() {
const { productId } = useParams();
const [product, setProduct] = useState(null);
const [error, setError] = useState('');
useEffect(() => {
const controller = new AbortController();
fetch(`/api/products/${productId}`, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
})
.then(setProduct)
.catch((err) => {
if (err.name !== 'AbortError') setError(err.message);
});
return () => controller.abort(); // cancel if the user navigates away
}, [productId]);
if (error) return <p>{error}</p>;
if (!product) return <p>Loading...</p>;
return <h2>{product.name}</h2>;
}
Three states are handled: loading (no product yet), error, and success. Showing something for each prevents a blank screen.
The URL in fetch starts with a slash, so it goes to the same server that delivered the page. During development the React dev server and your Express API usually run on different ports. Vite's server.proxy setting can forward /api requests to the backend, which avoids cross-origin errors without hard-coding a full address. In production, a base URL is often read from an environment variable instead.
The same pattern works for list pages. A product list might read a search term from the query string with useSearchParams, which you met in the previous lesson, and add it to the request URL. Put that value in the dependency array too, so typing a new search loads new results.
Sending form data with POST
To create something, send a POST request with a JSON body. The Content-Type header tells the server how to read the body, and JSON.stringify turns the object into text. After success, useNavigate moves the user to the new item's page.
function NewProductForm() {
const [name, setName] = useState('');
const [saving, setSaving] = useState(false);
const navigate = useNavigate();
async function handleSubmit(e) {
e.preventDefault();
setSaving(true);
const res = await fetch('/api/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name }),
});
setSaving(false);
if (!res.ok) return alert('Could not save');
const created = await res.json();
navigate(`/products/${created.id}`);
}
return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button disabled={saving}>{saving ? 'Saving...' : 'Save'}</button>
</form>
);
}
Disabling the button while saving stops double clicks from creating duplicates.
Why the AbortController matters
If a user clicks from product 1 to product 2 quickly, two requests are in flight. Without cancellation, the slower one might finish last and overwrite the screen with the wrong product. Aborting the old request in the effect's cleanup function ensures only the latest one can update state. It also avoids setting state after a component has unmounted.
Mistakes that break requests
- Sending an object as the body. Passing
body: { name }sends the text[object Object]. Always useJSON.stringify. - Forgetting the Content-Type header. An Express server using
express.json()ignores the body without it, soreq.bodyis empty. - Assuming fetch rejects on errors. A 404 or 500 still resolves. Check
res.ok, as both examples do. - Missing dependencies. Leaving
productIdout of the dependency array means the page never reloads when the URL changes.
Key points
Fetch inside useEffect keyed on route parameters, abort stale requests in cleanup, show loading and error states, send JSON with the right header, and navigate after a successful save. The next section uses these same requests to log users in.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.