In the previous tutorials, we saw Axios Authentication and how to make GET API call, POST API call with Axios. We assume that you know what CRUD operations are.
C- Create
R – Read
U – Update
D – Delete
When making a PUT request, we are actually updating the data. Now, we know that Axios is a promise-based HTTP Client JavaScript library for Node.js and Browser. In this tutorial, we will be learning how to make a PUT request with Axios.
Before starting with the code, make sure you install Axios in your project. The procedure was shared in the previous tutorial and we are sharing here again. We can then proceed further for calling update CRUD operation.
Table of Contents
Axios Installation & Import in React JS
Installation
With NPM: npm install axios
With Yarn: yarn add axios
Import
import axios from "axios";
PUT Requests with AXIOS (Update/PUT API Call)
We will use the axios.put() function to make a PUT request. The first parameter is the URL and the 2nd parameter is the HTTP request body. (This is the same as post request).
PUT API Call in Function Component
import React from "react";
import axios from "axios";
const baseURL = "https://jsonplaceholder.typicode.com/posts";
export default function App() {
const [post, setPost] = React.useState(null);
React.useEffect(() => {
axios.get(`${baseURL}/1`).then((response) => {
setPost(response.data);
});
}, []);
function updatePost() {
axios
.put(`${baseURL}/1`, {
title: "Hello World!",
body: "This is an updated post."
})
.then((response) => {
setPost(response.data);
});
}
if (!post) return "No post!"
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
<button onClick={updatePost}>Update Post</button>
</div>
);
}
PUT API Call in Class Based Component
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}
</>
)
}
}
PUT API Call with additional Headers & Error Handling
// Added Authorization Token in Headers
// Added a Catch Block for Catching all the API Errors
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 });
});
}
Extra Info: Content-Type (Headers)
Axios serializes the second parameter to JSON using the JSON.stringify() function. It also sets the content-type header to application/json (in case of Object as Body parameter), so frameworks like Express.js are able to convert the request body into vanilla JavaScript by itself.
By passing a string as body parameter to the axios.put() function, The Axios will set the content-type header to application/x-www-form-urlencoded. Again as in POST request, the request body will have key-value pairs separated by &.
// Passing a String as Body Parameter
const res = await axios.put('https://httpbin.org/put', 'hello=world');
res.data.headers['Content-Type']; // application/x-www-form-urlencoded
// Passing a Object as Body Parameter (Normal Request)
const res = await axios.put('https://httpbin.org/put', { hello: 'world' });
res.data.headers['Content-Type']; // application/json;charset=utf-8
PUT API Call with Async Await
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 })
}
PUT Request with AXIOS API
Similar to the HTTP Request but passing more relevant config data to Axios with parameters like method type or name, request API URL.
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 })
})
}
That’s it for the blog. We will see how to delete request in the next blog. Hope the tutorial was informative. Comment below with your doubts.
3 thoughts on “Call API – PUT Requests with AXIOS | React JS”