MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Handling HTTP POST, PUT, and DELETE Mutations0%
Study Materials
React.js for IntermediateProgress 0%
1.1Component Reusability and Polymorphic Components1.2Render Props Pattern in Modern React1.3Higher-Order Components vs Modern Hooks1.4Compound Components Pattern Explained
7.1Fetching REST APIs with Async Await and State7.2Handling HTTP POST, PUT, and DELETE Mutations7.3Introduction to TanStack Query for Server State7.4Managing Pagination, Caching, and Background Refetch
HomeTutorialsReact.js for IntermediateHandling HTTP POST, PUT, and DELETE Mutations
Introduction to TanStack Query for Server State

Handling HTTP POST, PUT, and DELETE Mutations

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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 (PUT replaces; PATCH modifies 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!

1User Clicks "Create Student"
2 │
3 ▼
4[Event Handler: handleSubmit]
5 ├─ Disable submit button (prevent double submissions)
6 ├─ Send fetch(url, { method: 'POST', body: JSON.stringify(data) })
7 ├─ Update local React state immutably upon success
8 └─ Show confirmation notification

2. Executing a POST Request

When sending data to a backend REST API:

  1. 1
    Set method: 'POST'.
  2. 2
    Specify 'Content-Type': 'application/json' in the headers object.
  3. 3
    Serialize the JavaScript payload using JSON.stringify(payload).
1import React, { useState } from 'react';
2 
3export default function CreateCourseForm({ onCourseCreated }) {
4 const [title, setTitle] = useState('');
5 const [price, setPrice] = useState(49);
6 const [isSubmitting, setIsSubmitting] = useState(false);
7 const [error, setError] = useState(null);
8 
9 const handleSubmit = async (e) => {
10 e.preventDefault();
11 setIsSubmitting(true);
12 setError(null);
13 
14 const payload = { title, price: Number(price) };
15 
16 try {
17 const response = await fetch('/api/courses', {
18 method: 'POST',
19 headers: {
20 'Content-Type': 'application/json',
21 'Authorization': `Bearer ${localStorage.getItem('token')}`
22 },
23 body: JSON.stringify(payload)
24 });
25 
26 if (!response.ok) {
27 const errorData = await response.json().catch(() => ({}));
28 throw new Error(errorData.message || 'Failed to create course');
29 }
30 
31 const createdCourse = await response.json();
32
33 // Update parent state immutably with newly created resource
34 onCourseCreated(createdCourse);
35 
36 // Reset form
37 setTitle('');
38 setPrice(49);
39 } catch (err) {
40 setError(err.message);
41 } finally {
42 setIsSubmitting(false);
43 }
44 };
45 
46 return (
47 <form onSubmit={handleSubmit} className="mutation-form">
48 <h3>Create New Course Track</h3>
49 {error && <p className="text-danger">{error}</p>}
50 
51 <input
52 type="text"
53 placeholder="Course Title"
54 value={title}
55 onChange={(e) => setTitle(e.target.value)}
56 required
57 />
58 
59 <input
60 type="number"
61 placeholder="Price ($)"
62 value={price}
63 onChange={(e) => setPrice(e.target.value)}
64 required
65 />
66 
67 {/* Disable button while network request is in-flight! */}
68 <button type="submit" disabled={isSubmitting}>
69 {isSubmitting ? 'Saving Course...' : 'Create Course'}
70 </button>
71 </form>
72 );
73}

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!
1// Optimistic Delete Example:
2const handleDelete = async (courseId) => {
3 // 1. Snapshot previous state for rollback
4 const previousCourses = courses;
5 
6 // 2. Optimistically remove from UI immediately (instant perceived performance!)
7 setCourses(prev => prev.filter(c => c.id !== courseId));
8 
9 try {
10 const res = await fetch(`/api/courses/${courseId}`, { method: 'DELETE' });
11 if (!res.ok) throw new Error('Delete failed on server');
12 } catch (err) {
13 // 3. Rollback on failure!
14 setCourses(previousCourses);
15 alert('Could not delete course. Restoring item.');
16 }
17};

Interactive Quiz• Knowledge Check

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 LessonNext Lesson
Fetching REST APIs with Async Await and StateIntroduction to TanStack Query for Server State

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext