Handle Axios Asynchronous HTTP POST Request in React

There are various HTTP methods (GET, POST, PUT, DELETE, etc..); these requests are used to communicate with the server in conjunction with the data.

Today, in this post, we will learn how to make an HTTP asynchronous post request in React application. To make the asynchronous POST request, we will use the Axios package along with React hooks. You will learn how to use Bootstrap in React, and we will give you a brief idea of how to design UI elements swiftly.

Additionally, we will show you how to set up a fake API for handling POST requests locally. We will use json server package to build the mock post API.

The post method is one of the supporting HTTP methods of the World Wide Web used to send data on the server.

Ideally, the web server receives the data contained in the body of the request message. Generally, it is used when uploading a file or storing a web form’s data on a server.

React Axios HTTP Asynchronous POST Request Example

  • Step 1: Create React Project
  • Step 2: Install Axios in React
  • Step 3: Set Up Component
  • Step 4: Create JSON Server
  • Step 5: Invoke HTTP POST Request
  • Step 6: Add Component in App Js
  • Step 7: Start Application

Create React Project

Let’s start with creating a new react application. Open your command prompt and use the suggested command to manifest a react app on your system.

npx create-react-app react-test

Make sure to get inside the app using the following command.

cd react-test

Install Axios in React

Making HTTP request is easy with axios, this package is available through npm registry. Here is the command that lets you add axios library in React.

npm install axios

Set Up Component

Next, create components folder, create the AsyncPostReq.js file and insert the provided code into the file.

import React from 'react'

export default function AsyncPostReq() {
  return (
    <div>
      
    </div>
  )
}

Create JSON Server

You may skip this step, if you already have have POST api. Otherwise, you can follow the given instructions to create the POST AI.

We will use the json-server to create the dummy API.

npm i json-server

Next, you need to create a db.json file at the root of your project folder.

Once the file server is created, append the given code int file.

{
  "posts": [
    {
      "id": 1,
      "title": "John Doe"
    }
  ]
}

Run the command to start the json server.

json-server --watch db.json

After running command, API source display on your terminal screen.

\{^_^}/ hi!

  Loading db.json
  Done

  Resources
  http://localhost:3000/posts

  Home
  http://localhost:3000

Invoke HTTP POST Request

The following code example serves two purposes, making the POST request and adding the data on the server and, on the other hand, fetching the data and displaying results on the frontend.

We are making HTTP POST requests inside the React functional component using the React useState, useEffect hooks.

Update components/AsyncPostReq.js file.

import React, { useState, useEffect } from 'react'
import axios from 'axios'

export default function AsyncPostReq() {
  const [users, initUser] = useState([])
  const [titleVal, setName] = useState('')

  const getReg = async () => {
    try {
      const res = await axios.get('http://localhost:3000/posts')
      initUser(res.data)
    } catch (e) {
      console.log(e)
    }
  }


  useEffect(() => {
    window.addEventListener('load', getReg)
    return () => {
      window.removeEventListener('load', getReg)
    }
  }, [users])


  const sumitForm = async (e) => { 
    e.preventDefault();
        
    const post = { title: titleVal };

    try {
      const res = await axios.post('http://localhost:3000/posts', post)
      console.log(res.data)
    } catch (e) {
      alert(e)
    }
  }

  return (
    <div className="container mt-5">
      <form onSubmit={sumitForm}>
        <div className="mb-3">
          <input
            type="text"
            className="form-control"
            value={titleVal}
            onChange={(e) => {
              setName(e.target.value)
            }}
            placeholder="Enter title"
          />
        </div>
        <div className="d-grid">
          <button type="submit" className="btn btn-primary mb-5">
            Add
          </button>
        </div>
      </form>

      <div className="alert alert-warning text-center" role="alert">
        Results
      </div>

      <ul className="list-group list-group-numbered">
        {users.map((res) => {
          return (
            <li
              className="list-group-item d-flex justify-content-between align-items-start"
              key={res.id}
            >
              <div className="ms-2 me-auto">
                <div className="fw-bold">{res.title}</div>
              </div>
            </li>
          )
        })}
      </ul>
    </div>
  )
}

Add Component in App Js

In this step, we have to import and call the AsyncPostReq component in src/App.js.

import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css';

import AsyncPostReq from './components/AsyncPostReq'

export default function App() {
  return (
    <div>
      <AsyncPostReq />
    </div>
  )
}

We are using bootstrap to design the ui elements. If you want to use the same then install the bootstrap package in your app.

Start Application

Finally, head over to console and use given command to invoke the react application.

npm start

Handle Axios Asynchronous HTTP POST Request  in React

Summary

The async/await pattern offers asynchronous, non-blocking code inscribed with minimal overhead and resembles almost like traditional synchronous blocking code.

This tutorial taught us to make HTTP POST and GET requests in the React app simultaneously using the Axios client and async/await pattern.