#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
HTTP

POST Request

A POST request sends data from your React app to a server so it can create something new, such as a user, a comment or an order. While a GET request asks the server for data, a POST carries data in its body. In React you usually send one when a form is submitted, using fetch with the method, headers and a JSON body.

What goes into a POST

  • Method: 'POST'. fetch defaults to GET if you leave this out.
  • Headers: 'Content-Type': 'application/json' tells the server how to read the body. Add an Authorization header if the API needs a token.
  • Body: a string. For JSON, convert your object with JSON.stringify().

A well-designed API answers with 201 Created and the new item, including the id the server assigned.

Submitting a form with fetch

import { useState } from 'react';

export default function AddTask({ onTaskAdded }) {
  const [title, setTitle] = useState('');
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState(null);

  async function handleSubmit(event) {
    event.preventDefault();
    if (!title.trim()) return;

    setIsSaving(true);
    setError(null);
    try {
      const response = await fetch('/api/tasks', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: title.trim(), done: false }),
      });
      if (!response.ok) throw new Error(`Could not save (${response.status})`);

      const created = await response.json();
      onTaskAdded(created);      // let the parent add it to its list
      setTitle('');              // clear the form
    } catch (err) {
      setError(err.message);
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <input value={title} onChange={(e) => setTitle(e.target.value)}
        placeholder="New task" aria-label="Task title" />
      <button disabled={isSaving}>{isSaving ? 'Saving...' : 'Add'}</button>
      {error && <p role="alert">{error}</p>}
    </form>
  );
}

Why a POST belongs in an event handler

In the previous lesson, data was loaded with useEffect, because loading should happen when the component appears. A POST is different: it should happen because the user did something. Putting it in an effect would send the request on every matching render, possibly creating duplicate records. Keep creation requests in submit or click handlers.

Updating the screen after saving

Once the server confirms the new item, the UI needs to show it. Two common approaches:

  1. Use the response. Add the returned object to the list in state, as onTaskAdded(created) does. This is fast and uses the real id from the server.
  2. Refetch. Call the GET request again. Simpler to reason about, but costs an extra round trip.

A third approach, called an optimistic update, adds the item to the list immediately and removes it if the request fails. It feels instant, but you need a temporary id and rollback logic, so start with the first approach.

Common mistakes with POST

Forgetting JSON.stringify is the classic one. Passing a plain object as body sends the text [object Object], and the server receives nothing useful. Forgetting the Content-Type header is the second: an Express server using express.json() will ignore the body and req.body will be empty.

Others to watch for: not calling event.preventDefault(), which lets the browser reload the page and cancel your request; and not disabling the button while saving, so a quick double click posts the same item twice.

The same pattern for other methods

Once POST works, updating and removing data look almost identical. A PUT or PATCH request sends a JSON body to a URL that includes the item's id, such as /api/tasks/12, and a DELETE request usually needs no body at all. Only the method, the URL and how you update state afterwards change.

What to remember

Send POST requests from event handlers, set the method and JSON content type, stringify the body, check response.ok, then use the returned item to update state and reset the form. Disable the submit button during the request to avoid duplicates.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course