Clue Mediator

POST request using axios with React Hooks

📅March 3, 2021

Today we’ll show you how to integrate POST request using axios with React Hooks. In the previous article, we had discussed about the GET request using axios.

In this article, we will show you a simple form to submit using a POST request in React Hooks.

Demo Application

Output - POST request using axios with React Hooks - Clue Mediator

Output - POST request using axios with React Hooks - Clue Mediator

Table of Contents: POST request using axios

  1. Installing axios
  2. POST request with a JSON body using axios
  3. POST request with HTTP header
  4. Example

1. Installing axios

Run the following command to install the axios with npm or yarn CLI.

npm CLI: `npm install axios`

yarn CLI: `yarn install axios`

2. POST request with a JSON body using axios

Let’s use the following syntax for the POST request.

const data = { name: 'name', job: 'job' };
axios.post('https://reqres.in/api/users', data)
  .then(response => {
    console.log("Status: ", response.status);
    console.log("Data: ", response.data);
  }).catch(error => {
    console.error('Something went wrong!', error);
  });

We have used the `post` method of the `axios` and attached the JSON body with the request.

3. POST request with HTTP header

We can use the third parameter to pass the HTTP headers. Look at the following code where we are passing the `Authorization` and `Custom-Header` along with the same request.

const data = { name: 'name', job: 'job' };
const headers = {
  'Authorization': 'Bearer my-auth-token',
  'Custom-Header': 'xxxx-xxxx-xxxx-xxxx'
};
axios.post('https://reqres.in/api/users', data, { headers })
  .then(response => {
    console.log("Status: ", response.status);
    console.log("Data: ", response.data);
  }).catch(error => {
    console.error('Something went wrong!', error);
  });

4. Example

Here, we will use the bootstrap package to design the page where we will create a form to submit the data using POST request via fake API.

App.js

import React, { useState } from 'react';
import axios from "axios";
import 'bootstrap/dist/css/bootstrap.min.css';

function App() {

  const [name, setName] = useState('');
  const [job, setJob] = useState('');
  const [loading, setLoading] = useState(false);
  const [isError, setIsError] = useState(false);
  const [data, setData] = useState(null);

  const handleSubmit = () => {
    setLoading(true);
    setIsError(false);
    const data = {
      name: name,
      job: job
    }
    axios.post('https://reqres.in/api/users', data).then(res => {
      setData(res.data);
      setName('');
      setJob('');
      setLoading(false);
    }).catch(err => {
      setLoading(false);
      setIsError(true);
    });
  }

  return (
    <div class="container p-3">
      <h5 class="d-inline-block mb-3">POST request using axios with React Hooks - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h5>
      <div 350="" style={{ maxwidth: }}>
        <div classnames="form-group">
          <label for="name">Name</label>
          <input type="text" class="form-control" id="name" placeholder="Enter name" value={name} onchange="{e" ==""> setName(e.target.value)} />
        </div>
        <div classnames="form-group">
          <label for="job" class="mt-2">Job</label>
          <input type="text" class="form-control" id="job" placeholder="Enter job" value={job} onchange="{e" ==""> setJob(e.target.value)} />
        </div>
        {isError && <small class="mt-3 d-inline-block text-danger">Something went wrong. Please try again later.</small>}
        <button type="submit" class="btn btn-primary mt-3" onclick={handleSubmit} disabled>{loading ? 'Loading...' : 'Submit'}</button>
        {data && <div class="mt-3">
          <strong>Output:</strong><br>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
        }
      </div>
    </div>
  );
}

export default App;

Run the above file and check the output in the browser.

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project