Clue Mediator

PUT request using axios with React Hooks

📅March 15, 2021

Today we will show you how to integrate PUT request using axios with React Hooks. In the previous articles, we had discussed the POST request and GET request using axios.

In this article, we will show you a simple form to update using a PUT request in React Hooks. Generally PUT requests are used to manage the update part.

Demo Application

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

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

Table of Contents: PUT request using axios

  1. Installing axios
  2. JSON body using axios">PUT request with a JSON body using axios
  3. PUT 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. PUT request with a JSON body using axios

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

const data = { name: 'name', job: 'job' };
axios.put('https://reqres.in/api/users/2', 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 `put` method of the `axios` and attached the JSON body with the request.

3. PUT request with HTTP header

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

const data = { name: 'name', job: 'job' };
const headers = {
  'Authorization': 'Bearer my-auth-token',
  'Custom-Header': 'xxxx-xxxx-xxxx-xxxx'
};
axios.put('https://reqres.in/api/users/2', 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-in-react" title="bootstrap package">bootstrap package to design the page where we will create a form to update the data using PUT 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.put('https://reqres.in/api/users/2', 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">PUT 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...' : 'Update'}</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 code 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