How to Use HTTP Post Method in React JS

In this article, we are going to learn about HTTP Post method in React JS. Making a request using Post method is a common thing when working with APIs. Since we know to access API, we mostly use fetch() and axios(). So we will make post requests using these two methods.

What is HTTP Post Method in React JS?

Post method is the same as its name, because it just posts the data to an endpoint, which is useful to store the data in the database. We use this method when we are aiming to post the data to web address, or you can say API.

Sending HTTP requests with any verb is made simple by the Fetch API (built-in) and libraries such as Axios. The Fetch API is a built-in browser method for performing HTTP requests, whereas Axios is an external package we must install in our project before using.

HTTP Post Method in React JS: Fetch()

The fetch() is a built-in JavaScript function which allows us to make network related requests. It is simple to use, and it doesn’t need any external package to use. It, basically, returns a promise that resolves to a response object, which is useful when accessing response data.

Let’s see an example, in the below example we have created a form with an input field and a button. When this form submits, then we call a function in which we have used fetch() with initial URL of API. Here, the default method is Get(), So we need to mention method as POST. Which makes a POST request to the specified URL with the data from the input field in the body of the request.

The fetch() function returns a promise, so we need to use await to wait for the response. then we have just parsed the data to JSON and log the result to console.

import React, { useState } from 'react';

function Example() {
  const [data, setData] = useState({});

  const handleSubmit = async (e) => {
    e.preventDefault();
    const response = await fetch('https://example.com/api/data', {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json'
      }
    });
    const result = await response.json();
    console.log(result);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" onChange={e => setData({...data, name: e.target.value})} />
      <button type="submit">Submit</button>
    </form>
  );
}

export default Example;

HTTP Post Method in React JS: axios()

Axios is another popular library for making network requests in React. It is basically an external library which need to be imported and install in the React application. Axios is a promise based library that makes it easy when working with network requests. It is also much powerful and flexible method then fetch as well. Here is a basic example for Post method with axios:

Now in the below example, we have to import axios, in order to work with network requests. To use POST method in axios we can use axios.post(). The axios.post() method returns a promise, so we use the await keyword to wait for the response. We then log the response data to the console.

One more thing to note that in order to use post method, we should use .catch(), in order to perform error handling and it is essential.

import axios from 'axios';

function Example() {
    const handleSubmit = async () => {
    try {
      const response = await axios.post('https://example.com/api/data', {
        name: "John Doe"
      });
      console.log(response.data);
    } catch (error) {
      console.error(error);
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Submit</button>
    </form>
  );
}

export default Example;

You may Also like:

Reactjs Guru
Reactjs Guru

Welcome to React Guru, your ultimate destination for all things React.js! Whether you're a beginner taking your first steps or an experienced developer seeking advanced insights.

React tips & tutorials delivered to your inbox

Don't miss out on the latest insights, tutorials, and updates from the world of ReactJs! Our newsletter delivers valuable content directly to your inbox, keeping you informed and inspired.

2 Comments

  1. ReactJS has revolutionized front-end web development with its component-based architecture and efficient rendering. As a popular JavaScript library, it is widely used in the industry to create interactive, scalable, and high-performance user interfaces. Whether you are a beginner or an experienced developer, learning ReactJS opens up exciting opportunities for your career in web development.

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents