Handling HTTP POST, PUT, and DELETE Mutations0%
Handling HTTP POST, PUT, and DELETE Mutations
Beginner12 min read•Updated: Jul 11, 2026
Handling HTTP POST, PUT, and DELETE Mutations
1. Mutations in Modern Web Apps
While fetching data (GET) is read-only, modifying server data is called a mutation:
POST: Creates a new resource (e.g. enrolling in a course, submitting a review).PUT/PATCH: Updates an existing resource (PUTreplaces;PATCHmodifies specific fields).DELETE: Removes an existing resource from the server.
Mutations are triggered by explicit user interactions (button clicks, form submissions). Unlike GET requests, mutations belong in event handlers, NOT in useEffect!
Output
User Clicks "Create Student"
│
▼
[Event Handler: handleSubmit]
├─ Disable submit button (prevent double submissions)
├─ Send fetch(url, { method: 'POST', body: JSON.stringify(data) })
├─ Update local React state immutably upon success
└─ Show confirmation notification
2. Executing a POST Request
When sending data to a backend REST API:
- 1Set
method: 'POST'. - 2Specify
'Content-Type': 'application/json'in theheadersobject. - 3Serialize the JavaScript payload using
JSON.stringify(payload).
JSX
import React, { useState } from 'react';
export default function CreateCourseForm({ onCourseCreated }) {
const [title, setTitle] = useState('');
const [price, setPrice] = useState(49);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
setIsSubmitting(true);
setError(null);
const payload = { title, price: Number(price) };
try {
const response = await fetch('/api/courses', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.message || 'Failed to create course');
}
const createdCourse = await response.json();
// Update parent state immutably with newly created resource
onCourseCreated(createdCourse);
// Reset form
setTitle('');
setPrice(49);
} catch (err) {
setError(err.message);
} finally {
setIsSubmitting(false);
}
};
return (
<form onSubmit={handleSubmit} className="mutation-form">
<h3>Create New Course Track</h3>
{error && <p className="text-danger">{error}</p>}
<input
type="text"
placeholder="Course Title"
value={title}
onChange={(e) => setTitle(e.target.value)}
required
/>
<input
type="number"
placeholder="Price ($)"
value={price}
onChange={(e) => setPrice(e.target.value)}
required
/>
{/* Disable button while network request is in-flight! */}
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Saving Course...' : 'Create Course'}
</button>
</form>
);
}
3. Handling DELETE with Optimistic UI vs Pessimistic UI
When deleting a resource:
- Pessimistic UI: Wait for the server to confirm deletion (HTTP 200/204), then remove it from the screen.
- Optimistic UI: Immediately remove the item from the screen, then send the network request in the background. If the request fails, roll back the UI and display an error alert!
JSX
// Optimistic Delete Example:
const handleDelete = async (courseId) => {
// 1. Snapshot previous state for rollback
const previousCourses = courses;
// 2. Optimistically remove from UI immediately (instant perceived performance!)
setCourses(prev => prev.filter(c => c.id !== courseId));
try {
const res = await fetch(`/api/courses/${courseId}`, { method: 'DELETE' });
if (!res.ok) throw new Error('Delete failed on server');
} catch (err) {
// 3. Rollback on failure!
setCourses(previousCourses);
alert('Could not delete course. Restoring item.');
}
};
Interactive Quiz
Practice Quiz
Question 1
Where should HTTP mutation requests (POST, PUT, DELETE) be executed in a React component?
Question 2
What header must be included when transmitting JSON payloads via POST or PUT requests?
Question 3
Why is disabling submit buttons (
disabled={isSubmitting}) critical during network mutations?Question 4
What is an "Optimistic UI update"?
Question 5
What is the difference between HTTP
PUT and PATCH?Next Lesson
Introduction to TanStack Query for Server State
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Fetching REST APIs with Async Await and State | Introduction to TanStack Query for Server State |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.