POST, PUT and DELETE Requests in React
POST, PUT, and DELETE are HTTP methods used to create, update, and remove data through an API. In React applications, these methods help developers build interactive features such as registration forms, product management systems, user profiles, task managers, and e-commerce applications.
Course Links: JustAcademy React JS Training | Register for React JS Course Demo
1. Introduction to POST, PUT and DELETE Requests
React applications often communicate with backend servers to manage application data. These HTTP methods allow the frontend to send instructions to an API.
- POST: Sends data to a server, commonly to create a new resource.
- PUT: Replaces a resource with the representation supplied in the request, or may create it if the API supports that behavior.
- DELETE: Requests the removal of a specified resource.
Example Scenario
Imagine you are developing a student management application.
- POST creates a new student record.
- PUT updates an existing student's complete record.
- DELETE removes a student record.
React Application
|
v
Backend API
|
+---- POST → Create a record
|
+---- PUT → Replace a record
|
+---- DELETE → Remove a record
2. Understanding POST Requests
A POST request sends data to a server for processing. It is commonly used to create new records, submit forms, register users, place orders, or send messages.
Common Uses of POST
- Creating a new user account.
- Adding a new product to an inventory.
- Submitting a contact form.
- Registering a student for a course.
- Creating a new task in a task management application.
Basic POST Request Using Fetch
async function createUser() {
try {
const response = await fetch(
"https://api.example.com/users",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Rahul",
email: "[email protected]"
})
}
);
if (!response.ok) {
throw new Error("Failed to create user");
}
const data = await response.json();
console.log("User created:", data);
} catch (error) {
console.error("Error:", error.message);
}
}
createUser();
Explanation
method: "POST" specifies the HTTP method.
headers describes the format of the request body.
Content-Type: application/json indicates that JSON data is being sent.
JSON.stringify() converts a JavaScript object into a JSON string.
response.ok checks whether the HTTP response indicates success.
response.json() parses a JSON response body.
try/catch handles request failures and errors explicitly thrown by the code.
Important: The example API URL is a placeholder. Replace it with an endpoint that supports creating users.
3. POST Requests in React Using useState
React forms commonly use useState to store input values. When the user submits the form, the application sends the values to the backend using a POST request.
Example: Create a New User
import { useState } from "react";
function CreateUser() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [message, setMessage] = useState("");
const [loading, setLoading] = useState(false);
async function handleSubmit(event) {
event.preventDefault();
setMessage("");
if (!name.trim() || !email.trim()) {
setMessage("Please enter your name and email.");
return;
}
setLoading(true);
try {
const response = await fetch(
"https://api.example.com/users",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: name.trim(),
email: email.trim()
})
}
);
if (!response.ok) {
throw new Error("Unable to create user");
}
setMessage("User created successfully!");
setName("");
setEmail("");
} catch (error) {
setMessage(error.message);
} finally {
setLoading(false);
}
}
return (
<form onSubmit={handleSubmit}>
<h2>Create User</h2>
<input
type="text"
placeholder="Enter name"
value={name}
onChange={event => setName(event.target.value)}
required
/>
<input
type="email"
placeholder="Enter email"
value={email}
onChange={event => setEmail(event.target.value)}
required
/>
<button type="submit" disabled={loading}>
{loading ? "Submitting..." : "Create User"}
</button>
{message && <p>{message}</p>}
</form>
);
}
export default CreateUser;
How It Works
- The user enters a name and email address.
useState stores the input values.
onSubmit runs when the form is submitted.
event.preventDefault() prevents the browser's default form submission and page reload.
- The application sends the data to the API using POST.
- The application displays a success or error message.
- The form fields are cleared after a successful response.
4. Understanding PUT Requests
A PUT request is used to replace the current representation of a resource with the data supplied in the request. It is commonly used when updating an existing record. Whether missing fields are removed, defaulted, or handled another way depends on the API contract.
Common Uses of PUT
- Updating a user's profile information.
- Replacing product details.
- Updating a student's record.
- Changing the details of an existing task.
- Replacing an existing address or configuration.
Basic PUT Request Using Fetch
async function updateUser() {
try {
const response = await fetch(
"https://api.example.com/users/1",
{
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Rahul Sharma",
email: "[email protected]"
})
}
);
if (!response.ok) {
throw new Error("Failed to update user");
}
const data = await response.json();
console.log("Updated user:", data);
} catch (error) {
console.error("Error:", error.message);
}
}
updateUser();
Explanation
method: "PUT" specifies that the request uses PUT.
/users/1 identifies the user resource in this example API.
body contains the replacement data being sent.
JSON.stringify() converts the object into a JSON string.
response.ok checks whether the server returned a successful HTTP status.
Important: Some APIs return status 204 No Content after a successful update. In that case, do not call response.json() because there is no response body to parse.
5. PUT Requests in React Using useState
A React form can allow users to edit existing information and submit the changes to a backend server using PUT.
Example: Update User Information
import { useState } from "react";
function UpdateUser() {
const [name, setName] = useState("Rahul");
const [email, setEmail] = useState("[email protected]");
const [message, setMessage] = useState("");
const [loading, setLoading] = useState(false);
async function handleUpdate(event) {
event.preventDefault();
setMessage("");
setLoading(true);
try {
const response = await fetch(
"https://api.example.com/users/1",
{
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name,
email
})
}
);
if (!response.ok) {
throw new Error("Unable to update user");
}
setMessage("User updated successfully!");
} catch (error) {
setMessage(error.message);
} finally {
setLoading(false);
}
}
return (
<form onSubmit={handleUpdate}>
<h2>Update User</h2>
<input
value={name}
onChange={event => setName(event.target.value)}
required
/>
<input
type="email"
value={email}
onChange={event => setEmail(event.target.value)}
required
/>
<button type="submit" disabled={loading}>
{loading ? "Updating..." : "Update User"}
</button>
{message && <p>{message}</p>}
</form>
);
}
export default UpdateUser;
Key Points
- Existing values are placed in the form when editing begins.
- The user changes the input fields.
- The PUT request sends the updated representation to the API.
- Loading and error states provide feedback during the operation.
- The backend determines whether the resource is updated or whether the request fails.
6. Understanding DELETE Requests
A DELETE request asks the server to remove a specific resource. In React applications, it is commonly used to delete users, products, tasks, comments, or other records.
Common Uses of DELETE
- Deleting a task from a task manager.
- Removing a product from an inventory.
- Deleting an existing user record.
- Removing a comment or post.
- Deleting a saved address.
Basic DELETE Request Using Fetch
async function deleteUser() {
try {
const response = await fetch(
"https://api.example.com/users/1",
{
method: "DELETE"
}
);
if (!response.ok) {
throw new Error("Failed to delete user");
}
console.log("User deleted successfully");
} catch (error) {
console.error("Error:", error.message);
}
}
deleteUser();
Explanation
method: "DELETE" tells the server which operation is requested.
/users/1 identifies the resource to delete in this example.
response.ok checks whether the HTTP response indicates success.
- The application can update its interface after the server confirms the operation.
Important: DELETE requests often return status 204 No Content. A successful response may have no JSON body, so check the status before attempting to parse a response body.
7. DELETE Requests in React
In a React list, a delete button can send a DELETE request for the selected record. After the API confirms success, the application can remove that record from the local state.
Example: Delete a User from a List
import { useState } from "react";
function UserList() {
const [users, setUsers] = useState([
{ id: 1, name: "Rahul" },
{ id: 2, name: "Priya" },
{ id: 3, name: "Amit" }
]);
const [message, setMessage] = useState("");
async function handleDelete(id) {
const confirmed = window.confirm(
"Are you sure you want to delete this user?"
);
if (!confirmed) return;
setMessage("");
try {
const response = await fetch(
`https://api.example.com/users/${id}`,
{ method: "DELETE" }
);
if (!response.ok) {
throw new Error("Unable to delete user");
}
setUsers(currentUsers =>
currentUsers.filter(user => user.id !== id)
);
setMessage("User deleted successfully.");
} catch (error) {
setMessage(error.message);
}
}
return (
<div>
<h2>User List</h2>
{message && <p>{message}</p>}
{users.length === 0 ? (
<p>No users available.</p>
) : (
<ul>
{users.map(user => (
<li key={user.id}>
{user.name}
<button onClick={() => handleDelete(user.id)}>
Delete
</button>
</li>
))}
</ul>
)}
</div>
);
}
export default UserList;
How It Works
- The application displays the list of users.
- The user clicks the Delete button next to a record.
- A confirmation dialog asks the user to confirm the action.
- The application sends a DELETE request for the selected user's ID.
- If the server confirms success,
filter() removes the user from the local React state.
- React re-renders the list without the deleted record.
Note: The users in this example are initial local state. A real application should load them from its API and keep the UI synchronized with the server response.
8. POST vs PUT vs DELETE
| Feature |
POST |
PUT |
DELETE |
| Primary purpose |
Submit data, often to create a resource |
Replace a resource representation |
Request resource removal |
| Request body |
Often included |
Usually included |
Usually not required |
| Typical endpoint |
/users |
/users/1 |
/users/1 |
| Example action |
Create a user |
Replace user details |
Delete a user |
| Idempotent |
Not generally |
Yes, by HTTP semantics |
Yes, by HTTP semantics |
| Common success codes |
201 Created or 200 OK |
200 OK, 201 Created, or 204 No Content |
200 OK or 204 No Content |
What does idempotent mean? An operation is idempotent when repeating the same request has the same intended effect on server state as performing it once. For example, repeating a PUT request with the same representation should leave the resource in the same state. Repeating a DELETE request should not remove anything additional, although the server may return a different status on later attempts.
9. Using Axios for POST, PUT and DELETE
Axios is an HTTP client library that can be used in React to simplify request handling. Install it in your project with the following command.
npm install axios
POST with Axios
import axios from "axios";
async function createProduct() {
try {
const response = await axios.post(
"https://api.example.com/products",
{
title: "Laptop",
price: 50000
}
);
console.log(response.data);
} catch (error) {
console.error("Create failed:", error.message);
}
}
PUT with Axios
async function updateProduct() {
try {
const response = await axios.put(
"https://api.example.com/products/1",
{
title: "Updated Laptop",
price: 55000
}
);
console.log(response.data);
} catch (error) {
console.error("Update failed:", error.message);
}
}
DELETE with Axios
async function removeProduct() {
try {
const response = await axios.delete(
"https://api.example.com/products/1"
);
console.log("Deleted successfully:", response.status);
} catch (error) {
console.error("Delete failed:", error.message);
}
}
Axios generally parses JSON responses automatically and exposes response data through response.data. Like Fetch, Axios requests still need suitable error handling and a backend API that supports the requested operation.
10. Handling Errors and Loading States
When sending POST, PUT, or DELETE requests, a React application should provide feedback to users while the operation is in progress and if it fails.
| State |
Purpose |
Example Message |
| Loading |
Indicates that the request is running. |
Saving changes... |
| Success |
Confirms that the server accepted the operation. |
Product created successfully. |
| Error |
Explains that the request did not succeed. |
Unable to update product. |
| Validation |
Identifies missing or invalid input. |
Please enter a valid email. |
| Confirmation |
Helps prevent accidental deletion. |
Are you sure you want to delete this record? |
Important Error-Handling Tips
- Check
response.ok when using Fetch.
- Use
try/catch to handle network failures and exceptions.
- Display helpful messages instead of exposing internal server details.
- Disable submit buttons while a request is in progress to reduce accidental duplicate submissions.
- Validate input on both the client and server.
- Do not update local state as though an operation succeeded before the API confirms success.
- For Axios, inspect the error response when available, while also handling cases where no response was received.
11. Important HTTP Status Codes
| Status Code |
Meaning |
Typical Use |
| 200 OK |
Request succeeded. |
Updated data returned or operation completed. |
| 201 Created |
A resource was created. |
Successful POST or PUT that creates a resource. |
| 204 No Content |
Request succeeded without a response body. |
Successful DELETE or update with no returned content. |
| 400 Bad Request |
Request is invalid. |
Incorrect or incomplete input. |
| 401 Unauthorized |
Authentication is missing or invalid. |
Login or valid credentials may be required. |
| 403 Forbidden |
Access is refused. |
User lacks permission to perform the operation. |
| 404 Not Found |
Resource was not found. |
Requested record does not exist. |
| 409 Conflict |
Request conflicts with current server state. |
Duplicate or conflicting record. |
| 500 Internal Server Error |
Server encountered an error. |
Unexpected backend failure. |
12. Best Practices for POST, PUT and DELETE Requests
- Use the correct HTTP method according to the API documentation.
- Use controlled inputs and validate user-provided data.
- Set the appropriate
Content-Type header when sending JSON.
- Use
JSON.stringify() to convert JavaScript objects into JSON strings for Fetch request bodies.
- Handle successful responses that contain no body.
- Provide loading, success, and error feedback.
- Ask for confirmation before potentially destructive actions.
- Keep the React UI synchronized with confirmed server changes.
- Use HTTPS for production APIs and implement authorization on the server.
- Never store private API secrets directly in frontend source code.
- Follow the backend's documented behavior for PUT versus PATCH.
- Use suitable safeguards against duplicate form submissions or repeated destructive actions.
13. Practical Project: Product Management Application
Project Objective: Build a React application that lets users create, update, and delete products through an API.
Project Features
- Create Product: Use POST to submit a product name, price, and category.
- Update Product: Use PUT to send the replacement representation for an existing product.
- Delete Product: Use DELETE to request the removal of a selected product.
- Display Products: Use a GET request to load products from the server.
- Loading Indicator: Show feedback during API operations.
- Error Messages: Display helpful information when a request fails.
- Form Validation: Ensure required fields and valid prices are supplied.
- Confirmation: Ask before deleting a product.
Example Product Structure
{
"id": 1,
"title": "Laptop",
"price": 50000,
"category": "Electronics"
}
Example API Endpoints
| Operation |
HTTP Method |
Example Endpoint |
| Get products |
GET |
/products |
| Create product |
POST |
/products |
| Replace product |
PUT |
/products/1 |
| Delete product |
DELETE |
/products/1 |
These are illustrative endpoint patterns. Your actual API may use different routes, validation rules, and response formats.
14. Common Mistakes to Avoid
- Using POST when the API expects PUT or another method.
- Forgetting to set the JSON content type when sending JSON.
- Sending a JavaScript object directly as a Fetch body instead of serializing it.
- Assuming that every successful request returns JSON.
- Calling
response.json() for a 204 No Content response.
- Removing a record from the UI before the server confirms deletion.
- Sending incomplete replacement data in a PUT request when the API expects a full representation.
- Assuming every API treats PUT as a partial update; PATCH is generally intended for partial modifications.
- Ignoring authorization failures and server-side validation errors.
- Using an example endpoint in production without confirming that it supports create, update, and delete operations.
15. Interview Questions and Answers
Q1. What is a POST request?
A POST request submits data to a server and is commonly used to create a new resource or trigger a server-side operation.
Q2. What is a PUT request?
A PUT request replaces the representation of a specified resource with the representation provided in the request. Some APIs also allow PUT to create a resource at a known URI.
Q3. What is a DELETE request?
A DELETE request asks the server to remove the specified resource.
Q4. What is the difference between PUT and PATCH?
PUT generally replaces a resource representation, whereas PATCH applies partial modifications to a resource.
Q5. Why is JSON.stringify() used in Fetch requests?
It converts a JavaScript object into a JSON string that can be sent in the request body.
Q6. Why is event.preventDefault() used in React forms?
It prevents the browser's default form submission behavior, allowing React to handle the submission without a normal page reload.
Q7. What does idempotent mean?
It means that repeating the same request has the same intended effect on server state as making it once. PUT and DELETE are defined as idempotent HTTP methods.
Q8. Why should DELETE operations have confirmation?
Confirmation can help prevent accidental removal of important records. The server must still enforce the appropriate permissions.
Q9. What is the purpose of a loading state?
A loading state indicates that an API operation is still in progress and can prevent users from submitting the same action repeatedly.
Q10. How do you handle an API error in React?
Check the HTTP response status, catch network or parsing errors, and display a helpful message to the user.
16. Practice Exercises
- Create a registration form and send the form data using POST.
- Build an edit form that updates an existing user using PUT.
- Create a task list with a Delete button for each task.
- Display loading and error states for all three request methods.
- Handle a successful response that returns status 204 without parsing JSON.
- Add form validation before sending a POST request.
- Use Axios to implement the same create, update, and delete operations.
- Test the application with successful requests, invalid data, missing resources, and server errors.
17. Conclusion
POST, PUT, and DELETE requests are important parts of API integration in React. POST is commonly used to submit or create data, PUT is used to replace a resource representation, and DELETE requests the removal of a resource. Combining these methods with React state, form handling, error management, and proper API validation helps developers create practical, interactive applications.
Explore more topics through JustAcademy React JS Training or Register for React JS Course Demo.
Official References