CRUD with fetch()
Complete create, read, update, delete flow — wiring a full REST API to a UI
Skills taught: api.crud-pattern, api.api-layer, api.full-stack-flow
Complete CRUD with a REST API
// ── API layer — all network calls in one place ──
const BASE = 'https://jsonplaceholder.typicode.com';
async function request(method, path, data) {
const opts = {
method,
headers: { 'Content-Type': 'application/json' },
};
if (data) opts.body = JSON.stringify(data);
const res = await fetch(BASE + path, opts);
if (!res.ok) throw new Error(`${method} ${path} → HTTP ${res.status}`);
if (res.status === 204) return null;
return res.json();
}
export const todosApi = {
getAll: () => request('GET', '/todos?_limit=10'),
getById: (id) => request('GET', `/todos/${id}`),
create: (data) => request('POST', '/todos', data),
update: (id, changes)=> request('PATCH', `/todos/${id}`, changes),
remove: (id) => request('DELETE', `/todos/${id}`),
};
// ── UI component wired to the API ──
import { todosApi } from './api/todos';
function TodoList() {
const [todos, setTodos] = React.useState([]);
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState(null);
const [newText, setNewText] = React.useState('');
// ── READ — fetch on mount ──
React.useEffect(() => {
todosApi.getAll()
.then(setTodos)
.catch(err => setError(err.message))
.finally(() => setLoading(false));
}, []);
// ── CREATE ──
async function addTodo(e) {
e.preventDefault();
if (!newText.trim()) return;
const optimistic = { id: Date.now(), title: newText, completed: false };
setTodos(prev => [optimistic, ...prev]); // optimistic update
setNewText('');
try {
const created = await todosApi.create({ title: newText, completed: false, userId: 1 });
setTodos(prev => prev.map(t => t.id === optimistic.id ? created : t));
} catch (err) {
setTodos(prev => prev.filter(t => t.id !== optimistic.id)); // revert
setError(err.message);
}
}
// ── UPDATE — toggle done ──
async function toggle(todo) {
setTodos(prev => prev.map(t => t.id === todo.id ? { ...t, completed: !t.completed } : t));
try {
await todosApi.update(todo.id, { completed: !todo.completed });
} catch (err) {
setTodos(prev => prev.map(t => t.id === todo.id ? todo : t)); // revert
}
}
// ── DELETE ──
async function remove(id) {
setTodos(prev => prev.filter(t => t.id !== id)); // optimistic
await todosApi.remove(id).catch(() => {
// Ideally refetch the list to restore state
});
}
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div>
<form onSubmit={addTodo}>
<input value={newText} onChange={e => setNewText(e.target.value)} placeholder="New todo" />
<button>Add</button>
</form>
{todos.map(todo => (
<div key={todo.id}>
<input type="checkbox" checked={todo.completed} onChange={() => toggle(todo)} />
<span style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>{todo.title}</span>
<button onClick={() => remove(todo.id)}>✕</button>
</div>
))}
</div>
);
}
Frequently Asked Questions
After I create a new item via POST, should I refetch the list or just update local state?
Both approaches work. **Refetch**: simple but causes a brief loading state. Use when the server may have applied transformations (added defaults, computed fields, sorted). **Update local state**: use the response from POST to add the new item to your local array — instant, no extra network call. Use when the POST response returns the complete item. The optimistic approach: add a temporary item before the POST, then replace it with the server response when it arrives. React Query/SWR handle this automatically — use `queryClient.invalidateQueries` to trigger a refetch after mutations.