Adding and deleting
The need: an employee adds a product from a form, sees why the add failed if it is refused, and deletes a product in one click. The list must reflect the database right after.
Related rules: Products · Errors and validation (API)
1. The form
'use client';
import { useActionState } from 'react';
import { addProduct } from '../app/actions';
export default function ProductForm() {
const [state, formAction, pending] = useActionState(addProduct, { error: null });
return (
<form action={formAction} className="card product-form">
<h2>Ajouter un produit</h2>
<div className="fields">
<label className="field-name">
Nom
<input name="name" required maxLength={120} />
</label>
<label>
Prix (€)
<input name="price" type="number" min="0" step="0.01" required />
</label>
<label>
Stock
<input name="stock" type="number" min="0" step="1" defaultValue="0" required />
</label>
<label className="field-wide">
Description
<input name="description" />
</label>
</div>
{state.error && <p role="alert" className="form-error">{state.error}</p>}
<button type="submit" className="button" disabled={pending}>
{pending ? 'Ajout…' : 'Ajouter'}
</button>
</form>
);
}Line 1: 'use client'. This component must react while sending, so it is also sent to the browser.
Line 7: useActionState(addProduct, { error: null }) connects the Server Action to the form. React returns three things:
| Value | Role |
|---|---|
state | What the action returned last time: { error } |
formAction | The function to pass to <form action> |
pending | true while sending |
Lines 30-33: the error is shown in a role="alert" (read by screen readers), and the button is disabled while sending to avoid a double add.
Why required, min, maxLength controls?
They avoid a useless round trip to the API for obvious errors. But they are easy to bypass: the real validation is the API's.
2. The actions
'use server';
import { revalidatePath } from 'next/cache';
import { createProduct, deleteProduct } from '../lib/products';
export async function addProduct(previousState, formData) {
try {
await createProduct({
name: formData.get('name'),
description: formData.get('description') ?? '',
price: formData.get('price'),
stock: Number(formData.get('stock')),
});
} catch (e) {
return { error: `Ajout impossible : ${e.message}` };
}
revalidatePath('/');
return { error: null };
}
export async function removeProduct(formData) {
await deleteProduct(formData.get('id'));
revalidatePath('/');
}Line 1: 'use server'. These functions never go to the browser. They can read API_URL.
addProduct (lines 6-20) receives previousState (required by useActionState) and formData, the form values.
- Line 12:
stockis converted to a number. A form always sends text, and the API expects an integer. - Line 11:
pricestays text. The API accepts"2.50"for a decimal, and we avoid JavaScript rounding. - Lines 14-16: on error, we return a state instead of throwing. The form displays it.
- Line 18:
revalidatePath('/')asks Next.js to rebuild the/page. The new list therefore comes from the API.
removeProduct (lines 22-25) receives the id from the Delete button's hidden field.
3. The API calls
// API_URL est lue au moment de la requête (et non au build) :
// la même image Docker fonctionne ainsi en dev comme en prod.
function productsUrl() {
const apiUrl = process.env.API_URL;
if (!apiUrl) {
throw new Error('API_URL is not defined');
}
return `${apiUrl}/api/products/`;
}
function checkResponse(response) {
if (!response.ok) {
throw new Error(`API responded with status ${response.status}`);
}
}
export async function fetchProducts() {
const response = await fetch(productsUrl(), { cache: 'no-store' });
checkResponse(response);
const data = await response.json();
// DRF renvoie { results: [...] } quand la pagination est activée.
return Array.isArray(data) ? data : data.results ?? [];
}
export async function createProduct(product) {
const response = await fetch(productsUrl(), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(product),
});
checkResponse(response);
return response.json();
}
export async function deleteProduct(id) {
const response = await fetch(`${productsUrl()}${id}/`, { method: 'DELETE' });
checkResponse(response);
}createProduct sends the product as with the Content-Type: application/json header. Without it, Django REST Framework would not read the body as JSON.
deleteProduct builds …/api/products/3/. The trailing slash is mandatory: Django rejects …/products/3 without it.
Pitfalls
Delete errors are not caught
removeProduct returns no error state. If the API refuses the delete, Next.js shows its error page. It is listed in the Limits.
The server must reach the API
The actions run in the web container. That container must reach API_URL, not the employee's browser.
What to remember
- The form is the only client component; the actions run on the server.
- An add error is returned as state, not thrown.
- After each change,
revalidatePath('/')re-reads the database: no local state to keep in sync.