Sending POST Requests in React
In this lesson, you will learn how to send data from a React application to an API using the HTTP POST method. You will understand request headers, JSON request bodies, form handling, server responses, and error handling.
1. What Is a POST Request?
An HTTP POST request is commonly used to submit data to a server. For example, a React application may submit a registration form, create a new student record, or send product information to a backend.
With a POST request, the client can include data in the request body. The server processes that data according to the API's rules and returns an HTTP response.
Real-Life Examples
- Submitting a student registration form.
- Creating a new course record.
- Submitting a contact form.
- Creating an order in an e-commerce application.
2. GET vs POST
GET and POST are HTTP methods used for different purposes. GET is generally used to retrieve data, while POST is often used to submit data for processing or resource creation.
- GET: Requests information from an API.
- POST: Sends data in the request body.
const response = await fetch("/api/students");
const students = await response.json();
const response = await fetch("/api/students", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Samadhan",
course: "React"
})
});
/api/students is an illustrative URL.
Your backend must implement and support that endpoint for the
request to work.
3. How a POST Request Works
The React component collects the user's input and sends it to the API. The backend receives the request, validates the data, performs the required operation, and returns a response. React then updates its interface based on the result.
4. Understanding the Fetch POST Options
Fetch accepts a URL and an optional configuration object. The configuration object allows you to specify the HTTP method, headers, and request body.
fetch("https://api.example.com/students", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Samadhan",
course: "React"
})
});
Explanation
-
method: "POST"tells Fetch to send a POST request. -
headerscontains metadata about the request. -
Content-Type: application/jsontells the server that the request body is JSON. -
bodycontains the data being submitted. -
JSON.stringify()converts a JavaScript object into a JSON string.
JSON.stringify(). A plain JavaScript object cannot
be used directly as the Fetch request body.
5. Create a React Form
Before sending data, create a form to collect the user's input. In React, controlled inputs use state to keep their values synchronized with the component.
import { useState } from "react";
function StudentForm() {
const [name, setName] = useState("");
const [course, setCourse] = useState("");
return (
<form>
<label>
Student Name
<input
type="text"
value={name}
onChange={event => setName(event.target.value)}
/>
</label>
<label>
Course
<input
type="text"
value={course}
onChange={event => setCourse(event.target.value)}
/>
</label>
<button type="submit">Submit</button>
</form>
);
}
export default StudentForm;
Understanding the Form
useState("")initializes each input with an empty string.valueconnects the input to its state value.onChangeupdates state when the user types.type="submit"makes the button submit the form.
6. Send Form Data Using a POST Request
The following complete component submits student details to an example endpoint. It prevents the browser's default form submission, sends JSON to the server, and displays a success or error message.
import { useState } from "react";
function StudentForm() {
const [name, setName] = useState("");
const [course, setCourse] = useState("");
const [message, setMessage] = useState("");
const [loading, setLoading] = useState(false);
async function handleSubmit(event) {
event.preventDefault();
setMessage("");
setLoading(true);
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: name,
body: course,
userId: 1
})
}
);
if (!response.ok) {
throw new Error("Failed to submit data");
}
const result = await response.json();
setMessage(
`Data submitted successfully. Response ID: ${result.id}`
);
setName("");
setCourse("");
} catch (error) {
setMessage(error.message || "Something went wrong");
} finally {
setLoading(false);
}
}
return (
<div>
<h2>Student Registration</h2>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="studentName">Student Name</label>
<input
id="studentName"
type="text"
value={name}
onChange={event => setName(event.target.value)}
required
/>
</div>
<div>
<label htmlFor="course">Course</label>
<input
id="course"
type="text"
value={course}
onChange={event => setCourse(event.target.value)}
required
/>
</div>
<button type="submit" disabled={loading}>
{loading ? "Submitting..." : "Submit"}
</button>
</form>
{message && <p role="status">{message}</p>}
</div>
);
}
export default StudentForm;
Step-by-Step Explanation
-
handleSubmitruns when the form is submitted. -
event.preventDefault()prevents a normal browser form submission and page reload. -
setLoading(true)indicates that the request is in progress. -
fetch()sends a POST request with JSON data. -
response.okchecks whether the server returned a successful HTTP status. -
response.json()reads the response body. -
setMessage()displays feedback to the user. -
finallyresets the loading state regardless of whether the request succeeds or fails.
7. Understanding the POST Response
After processing a POST request, an API may return the created resource, an identifier, a status message, or another response defined by the endpoint.
{
"title": "Samadhan",
"body": "React",
"userId": 1,
"id": 101
}
In this example, id represents an identifier returned
by the API. The actual response structure depends on the server.
Example UI Message
Data submitted successfully. Response ID: 101
8. Common Mistakes
- Forgetting event.preventDefault(): The browser may perform a normal form submission and reload the page.
- Forgetting JSON.stringify(): Convert the JavaScript object into a JSON string before sending it as a JSON request body.
- Missing Content-Type: When sending JSON, identify the body format with the appropriate request header.
-
Ignoring HTTP errors: Check
response.okbefore treating the request as successful. - Allowing duplicate submissions: Disable the submit button while the request is running when appropriate.
- Assuming the data is saved: A test API may simulate a POST response without storing data permanently.
- Exposing sensitive information: Never place private API secrets or server credentials in frontend code.
9. Practice Tasks
Task 1: Create a Contact Form
Create a React form with name, email, and message fields. Collect the input values using useState.
Task 2: Send a POST Request
Send the contact form data using Fetch, the POST method, a JSON Content-Type header, and JSON.stringify().
Task 3: Show a Loading State
Disable the submit button while the request is in progress and change its text to "Submitting...".
Task 4: Display the Response
Parse the response JSON and display a suitable success message after checking the HTTP status.
Task 5: Handle Errors
Use try/catch/finally to handle request failures and restore the submit button after the operation finishes.
Summary
In this lesson, you learned how POST requests submit data to an API, how to configure Fetch with an HTTP method and headers, how JSON.stringify converts an object into a request body, and how to collect form values using React state. You also learned to prevent default form submission, process API responses, display loading and success messages, and handle errors with try/catch/finally. In the next lesson, you will learn more about handling API errors and building reliable error-handling logic in React.