Author -  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.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY