React

React Axios Send Asynchronous HTTP Post Request Tutorial

HTTP requests are the lifeline of sites and applications; due to HTTP requests, subtle communication is established between client and server.

HTTP is an application layer protocol that stands for Hypertext Transfer Protocol; in this post, we will discuss asynchronous HTTP post requests.

We will show you the holistic approach to make HTTP asynchronous post requests in React using Axios javascript client.

An asynchronous request does not interfere with another operation, and at the same time, we can execute another operation. Thanks to this paradigm for not blocking the javascript engine of the browser.

Axios is a profound package, especially developed to handle relentless HTTP requests. This tutorial will show you how to handle HTTP Post requests; however, it is not limited to only sending data to the server.

Here are the other Axios HTTP methods and options about which we will talk in upcoming tutorials.

  • get(url[, config])
  • request(config)
  • delete(url[, config])
  • head(url[, config])
  • options(url[, config])
  • post(url[, data[, config]])
  • put(url[, data[, config]])
  • patch(url[, data[, config]])

How to Use Axios to Make Asynchronous HTTP Post Request in React

  • Step 1: Install New Application
  • Step 2: Add Axios and Bootstrap Packages
  • Step 3: Set Up Fake Server
  • Step 4: Create Component File
  • Step 5: Register Component in React
  • Step 8: Run App Development Server

Install New Application

If you are just starting fresh, then you need to install a blank react app. You can do it by using the given command.

npx create-react-app react-planet

Ensure to get into the project folder.

cd react-planet

Add Axios and Bootstrap Packages

To make the flawless http requests, requires to add axios library in react. Moreover, we are also adding the bootstrap, hence use both the commands altogether through the command prompt of the terminal.

npm install axios bootstrap

Bootstrap has to be added into the App.js file, it will open the gates to create ui modules in your react app development journey.

import 'bootstrap/dist/css/bootstrap.min.css'

Set Up Fake Server

In this step, we will set up the fake server, we will take help of json server package.

This library is easy to use, you can include it in react to build the fake apis.

npm i json-server

While the json-server is installing, besides it created a db.json file.

Next, open the db.json file and add the given code into the file.

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

By default, this server starts on port 3000; apparently, the react app is working on the same port. We may use the –port attribute to run the API server on the diffrent port.

json-server --watch db.json --port 3001

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

\{^_^}/ hi!

  Loading db.json
  Done

  Resources
  http://localhost:3001/users

  Home
  http://localhost:3001

Create Component File

We are about to show you how to conjugate everything in the separate file to make the http post request module.

So you have to create HttpPost.js file in the components/ folder. Also, add the following code into the file.

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

export default function HttpPost() {
  const [userName, createUser] = useState('')

  const onSubmit = async (e) => {
    e.preventDefault()

    const post = { userName: userName }

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

  return (
    <div className="container mt-2">
      <h2>React HTTP Post Request Example</h2>
      <form onSubmit={onSubmit}>
        <div className="mb-2 mt-3">
          <input
            type="text"
            placeholder="Name"
            className="form-control"
            onChange={(event) => {
              createUser(event.target.value)
            }}
            value={userName}
          />
        </div>

        <button type="submit" className="btn btn-danger">
          Create
        </button>
      </form>
    </div>
  )
}

Register Component in React

Once again open the App.js file and register the HttpPost component.

import React from 'react'

import HttpPost from './components/HttpPost'
import 'bootstrap/dist/css/bootstrap.min.css';


export default function App() {
  return (
    <div className="App">
      <HttpPost />
    </div>
  )
}

Run App Development Server

Now, you must have an urge to see how it looks on the browser. Well, for that, you have to run the app development server.

Open the console, type the command and run the server.

npm start

You have to take help of the given url to test the post request in the browser.

http://localhost:3000/

After creating the user, you can check how the data is updating on the test api.

http://localhost:3001/users

Summary

React development is gradually shifting from class component to functional component. In this change, we are also with you; we also took the initiative to create more tutorials from functional outlook.

Similarly, in this tutorial, we learned how to use react hooks and Axios to manage asynchronous HTTP post request in React applications.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.

Recent Posts

How to Add Active Class in Map Items in React Js

In this quick tutorial, we will show you how to quite easily add the active…

2 days ago

How to Create and Use Redux Store in React Js

In this tutorial, we will learn how to create a Redux Store in React application.…

5 days ago

How to Build Dynamic Load More Feature in React Js

This detailed guide will cover how to create the Load More button and display data…

1 week ago

How to Integrate Redux Persist to React Redux Store

In this tutorial, we will step by step learn how to configure redux persist in…

2 weeks ago

React Redux Save Data in Local Storage with Persist Tutorial

In this comprehensive tutorial, we will learn how to persist redux store's states in React…

2 weeks ago

React Js Tailwind CSS Add Light and Dark Mode Toggler Tutorial

In this guide, we are going to learn how to add dark mode and light…

2 weeks ago