Menu

React POST Requests: Send Data Using Fetch API

Sending Data with POST Requests

What is a POST Request?

A GET request reads data. A POST request sends data to the server — submitting a form, creating an enrolment, posting a comment.

Example

src/components/EnrolmentForm.jsx

jsx

import { useState } from "react";

function EnrolmentForm() {
  const [formData, setFormData] = useState({ name: "", course: "" });
  const [submitting, setSubmitting] = useState(false);
  const [message, setMessage] = useState(null);

  function handleChange(event) {
    const { name, value } = event.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  }

  async function handleSubmit(event) {
    event.preventDefault();
    setSubmitting(true);
    setMessage(null);

    try {
      const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData)
      });

      if (!response.ok) {
        throw new Error("Enrolment failed. Please try again.");
      }

      await response.json();
      setMessage({ type: "success", text: "Enrolment successful" });
      setFormData({ name: "", course: "" });
    } catch (err) {
      setMessage({ type: "error", text: err.message });
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        name="name"
        value={formData.name}
        onChange={handleChange}
        placeholder="Your name"
      />
      <input
        name="course"
        value={formData.course}
        onChange={handleChange}
        placeholder="Course name"
      />

      <button type="submit" disabled={submitting}>
        {submitting ? "Submitting..." : "Enrol"}
      </button>

      {message && (
        <p className={message.type}>{message.text}</p>
      )}
    </form>
  );
}

export default EnrolmentForm;

How It Works

  • method: "POST" tells the server this is a create request.
  • headers: { "Content-Type": "application/json" } tells the server what format the body is in. Leaving this out is a frequent cause of rejected requests.
  • body: JSON.stringify(formData) converts the JavaScript object into a JSON string. The body must be a string.
  • disabled={submitting} prevents double submissions while the request is in flight.
  • The button label changes during submission, so the user knows something is happening.

Output

Clicking "Enrol" disables the button and changes its text, then shows a success message and clears the form.


ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details