by Sai gowtham

How to make a post request in React hooks

Learn, how to make a post request in react hooks using fetch API.

Making a post request in React hooks

This below example sends an http post request to the json placeholder api using fetch where useState() hook is used to store the user entered data.

App.js
import React, { useState } from "react";

function App() {
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");

  const onTitleChange = e => setTitle(e.target.value);  const onBodyChange = e => setBody(e.target.value);
  const handleSubmit = e => {
    e.preventDefault();

    const data = { title, body };
    const requestOptions = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data)
    };
    fetch("https://jsonplaceholder.typicode.com/posts", requestOptions)      .then(response => response.json())      .then(res => console.log(res));  };

  return (
      <div className="App">
        <form>
          <input  placeholder="Title" value={title}            onChange={onTitleChange} required />          <textarea placeholder="Body" value={body}            onChange={onBodyChange} required />          <button type="submit" onClick={handleSubmit}>
           Create Post
          </button>
        </form>
      </div>
  );
}

export default App;

In the above code, we first imported useState() hook from the react then we initialized a state inside the App component which are title, body.

The onTitleChange() and onBodyChange() functions are used to set the user entered data to title and body properties.

If we click on a Create Post button it will call the handleSubmit() function, which sends a post request to the api.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course