Home > ReactJS > How to Make Axios PUT (Update) Request in React?

How to Make Axios PUT (Update) Request in React?

In the last two tutorials, we already learned about Axios GET requests and Axios POST requests. Now we will learn about how we can make a PUT request using Axios to update the data in the react application.

We will make a PUT request to update the data in the database. We will send request parameters in the PUT request and then update the data for parameters. Also, take some examples to send HTTP headers, errors handle, and javascript async/await expression in a PUT request.

So let’s start to make an Axios PUT request to update the data in the database table and show the success response.

Axios HTTP PUT (Update) Request in React

To install the React application on your machine you can check the details tutorial on how to install react and create an application.

You will need first install the Axios package with the help of NPM. In the next section, we will look at some of the most basic examples of Axios PUT requests. We will also make use of Axios API to make PUT requests.

Install Axios From NPM

You have to run the following NPM command to install the Axios package in your project. Make sure you are in the right directory.

The following command will install all the dependencies for the Axios package, so you can import it into your react component and then use it.

Command to install the Axios package
npm install axios
// OR //
yarn add axios
Syntax to import the Axios package
import axios from "axios";

Axios PUT Request in Class-Based Component

We will take a class-based react component to make a PUT request using the Axios package. Let’s make handleUpdate() the function to make a PUT request click on the button that has an onclick function referred to the handleUpdate function.

The handleUpdate() the function runs only when you update the employee data and click on the Update button. See the following reference code.

import React from 'react';
import axios from 'axios';

export default class CreateEmployee extends React.Component {
    state = {
        status: "",
        employee_name: "",
        employee_salary: "",
        employee_age: ""
    }

    handleUpdate = () => {
        const { employee_name, employee_salary, employee_age } = this.state;

        axios.put(`http://dummy.restapiexample.com/api/v1/update/5`, {
            employee_name: {employee_name},
            employee_salary: {employee_salary},
            employee_age: {employee_age}
        })
        .then(response => {
            this.setState({ status: response.status });
        })
    }

    render() {
        const { status, employee_name, employee_salary, employee_age } = this.state;
        return (
            <>
                <h4>Axios PUT Request Example in React</h4>

                <input type="text" name="employee_name" value={employee_name}/>
                <input type="text" name="employee_salary" value={employee_salary}/>
                <input type="number" name="employee_age" value={employee_age}/>

                <input type="button" name="update" value="Update" onClick={this.handleUpdate}/>

                {status && status}
            </>
        )
    }
}

In the above code, we made a PUT request in the react function called handleUpdate() and then show the result status in render() method.

Axios PUT Request in Function-Based Component

Now we will take a function-based react component to make PUT requests using the Axios. In the function-based component, we also have to make a handleUpdate() function to run the Axios PUT request.

And the handleUpdate() function only runs when clicking on the Update button that refers to this function.

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

function CreateEmployee() {
    const [status, setStatus] = useState('');
    const [employee_name, setEmployeeName] = useState("");
    const [employee_salary, setEmployeeSalary] = useState("");
    const [employee_age, setEmployeeAge] = useState("");

    handleUpdate() {
        axios.put(`http://dummy.restapiexample.com/api/v1/update/8`, {
            employee_name: {employee_name},
            employee_salary: {employee_salary},
            employee_age: {employee_age}
        })
        .then(response => {
            setStatus(response.status);
        })
    }


    return (
        <>
            <h4>Axios PUT Request Example in React</h4>

            <input type="text" name="employee_name" value={employee_name}/>
            <input type="text" name="employee_salary" value={employee_salary}/>
            <input type="number" name="employee_age" value={employee_age}/>

            <input type="button" name="submit" value="Update" onClick={handleUpdate}/>

            {status && status}
        </>
    );
}

In the above react example, we use the Axios to make a PUT request in the handleUpdate() function and set the response in the state using the useState hook. And then return a success message from the state in return.

Axios PUT Request with Error Handling

In the above two examples, we used only then() promise to return the response and not handle any error while updating the data. So now in this case we will handle the error, and we will use the catch() promise method. Let’s see the example code.

handleUpdate = () => {
    const { employee_name, employee_salary, employee_age } = this.state;
    axios.put(`http://dummy.restapiexample.com/api/v1/update/14`, {
        employee_name: {employee_name},
        employee_salary: {employee_salary},
        employee_age: {employee_age}
    })
    .then(response => {
        this.setState({ status: response.status })
    })
    .catch(error => {
        this.setState({ errorMessage: error.message });
    });
}

This HTTP PUT request with Axios will send the data to update and return the response but if any error exists then the catch() method will return the error message and you can print that error in the component using the state.

Axios PUT Request with HTTP Headers

To send the HTTP headers with PUT requests using the Axios, you have to pass the third parameter as an object of header values. Look at the following example for reference.

handleUpdate = () => {
    const { employee_name, employee_salary, employee_age } = this.state;
    const headers = {
        'Authorization': 'Bearer token_value',
    };
    axios.put(`http://dummy.restapiexample.com/api/v1/update/35`, {
        employee_name: {employee_name},
        employee_salary: {employee_salary},
        employee_age: {employee_age}       
    }, { headers })
    .then(response => {
        this.setState({ status: response.status })
    })
    .catch(error => {
        this.setState({ errorMessage: error.message });
    });
}

In the above code example, we make a const for the header value and then pass it into Axios PUT request as a third parameter. You can also pass any customer headers in that object if you want to do so.

Axios PUT Request Using async/await

In the above examples, we used then() promise method to wait till the promise returns the response and then continue on further action. But you can also do the same thing with async and await expressions of javascript.

You have to add the async expression before the name of the function and then use the await expression with the Axios request action. See the following example to better understand.

handleUpdate = async() => {
    const { employee_name, employee_salary, employee_age } = this.state;
    const response = await axios.put(`http://dummy.restapiexample.com/api/v1/update/17`, {
        employee_name: {employee_name},
        employee_salary: {employee_salary},
        employee_age: {employee_age}    
    });
    this.setState({ status: response.status })
}

The above function will not proceed with further action until the request gets a response.

Axios PUT Request Using Axios API

The Axios API is the same way to make an HTTP request, you just have to pass the relevant config data to Axios as parameters like method name, request URL, response type, etc.

handleUpdate = () => {
    const { employee_name, employee_salary, employee_age } = this.state;
    axios({
        method: 'put',
        url: 'http://dummy.restapiexample.com/api/v1/update/24',
        data: {
            employee_name: {employee_name},
            employee_salary: {employee_salary},
            employee_age: {employee_age}
        }
    })
    .then(response => {
        this.setState({ status: response.status })
    })
}

All the above examples, you can customize to make Axios PUT requests and send the body data with that and then set the response in the state and show it on a frontend popup notification like “Record has been updated successfully.”

Conclusion

So in this tutorial example, you learned about the installation of the Axios package and how to import and use it. In this article, we covered how to make a PUT request using the Axios package in the React application.

We made different ways of using the Axios PUT request to handle the error, with custom headers, using async/await expressions and Axios API.

FAQs

What is an Axios PUT request in React?

An Axios PUT request in React is a method used to update data on a server by sending a request to a specified URL. It is commonly used in React applications to modify existing resources on the server, such as updating user profiles or editing content.

How do I make an Axios PUT request in a React component?

To make an Axios PUT request in a React component, you can use the Axios library to send a PUT request to the server using axios.put() method. Typically, you would define the request parameters, such as the URL and data to be updated, within the Axios request configuration.

What is the difference between Axios PUT and Axios POST requests in React?

Axios PUT requests are used to update existing resources on the server, while Axios POST requests are used to create new resources. In React applications, understanding this distinction is crucial for handling data manipulation and interaction with the server effectively.

Can I handle Axios PUT request errors in React?

Yes, you can handle errors in Axios PUT requests in React by utilizing the promise-based structure of Axios. You can use the .then() method for successful responses and the .catch() method to capture and manage errors, ensuring a robust error-handling mechanism in your React application.

Are there any best practices for using Axios PUT requests in React?

It is recommended to encapsulate Axios PUT requests within functions or components to promote reusability. Additionally, consider implementing loading indicators or error messages to enhance the user experience while the PUT request is being processed. Properly managing the state and handling edge cases will contribute to a more robust and reliable React application.

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment