Using Axios in React - Learn All About React Query With Axios

Using Axios in React – Learn All About React Query With Axios

The most frequent task while working with web apps in React is interacting with backend services. Typically, the HTTP protocol is used for this to learn more about using Axios in React.

We can all easily fetch data and send HTTP queries with the help of the widely used XML Http Request interface and Fetch API.

In this article, we will learn about an awesome Javascript library called Axios and some key features of Axios that have helped frontend developers to communicate with the backend in React.

What is Axios in React?

Axios is a Javascript library that connects to the backend API and controls HTTP protocol requests. It allows us to handle asynchronous code and helps to reduce loading time.

Add Axios to your project.

Run the following command to install Axios using npm:

Example

	
npm i axios

Get Request Using Axios

First, create a component; we have created here component, namely Posts and put below code in the Posts.js file :

Example

	
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const Posts - () -> {
const [post, setPost] = useState({});
useEffect (() => {
axios.get('url/posts') .then((response) => setPost (response?.data));
}, []);
return (
<div>
);
};
Posts
{post.map((item, i) => {]
return (
<div key={i}>
<p>{item.name}</p>
</div>
I
})}
</div>

First, import Reacts useEffect and useReact hooks and also import Axios to make http requests. Then, with the help of the useEffect, we can use the get method to make a get request to our endpoints and then use the then() method to get the response data and update the post’s state.

We receive an object in the response, and after assigning the object to the post’s state, we can use it in the component.

Post/Put request using Axios

Create the AddPosts.js file and add the below code to the file :

Example

	
import React, { useState } from 'react
import axios from 'axios’
const AddPosts = () =› {
const [postData, setPostData] = useState({
postName:
});
const handleChange = (e) =› {
e.preventDefault();
setPostData(H
postName: e.target.value,
const submitForm = (e) => {
e.preventDefault();
axios.post (url/posts, { postData }) .then ( (response) =› {
console.log (response);
});
};

Example

	
return (
‹div>
<p>Add Posts</p>
‹div>
<form onSubmit-{submitForm}>
<label>
Post Name
<input type-"text" name- "postName" onChange-(handleChange)
‹button type-"submit"›Add</button>
</label>
</ form>
</div>
</div>
export default AddPosts;

We halt the form’s default operation by using the SubmitForm function. The state is then updated to reflect the user’s input. The POST method returns the response object with data that we can utilize inside the then() method.

In the same way, we can use the put method to update the data. For that, we need the axios.put method.

Schedule an interview with React developers

Delete Request Using Axios

We can use the delete method to delete items using Api. For that, create a DeletePost.js file and add the following code :

Example

	
return(
<div>
<p>Delete Posts</p>
‹div>
<form onSubmit={handleDelete}>
<label>
Post Id
<input type-"number" name-"id" onChange-(handleChange /
<button type-"submit"›Delete‹/button›
</label>
</form>
</div>
</div>
);
};
export default DeletePosts;

Here also, the response object contains information about api response.

Example

	
import React, { useState } from 'react';
import axios from 'axios"
const DeletePosts = () =› {
const [postData, setPostData] = useState {
id:
});
const handleChange = (e) =› {
e.preventDefault ();
setPostData(K
id: e.target .value,
b);
};
const handleDelete = (e) =› {
e.preventDefault ();
axios.delete(url/posts/${postData.id*).then((response) =› {
console. log (response); });};

Handling Error using Axios

Sometimes there may be problems with the passing data, the wrong url used or maybe backend\network issues. All those types of Errors also can be handled using Axios. Let’s See the below example for your reference :

Example

	
useEffect (() =›
{
axios
get ('url/posts")
.then ( (response) -&gt; setPost (response? .data))
.catch( (error) -&gt; console. log(error));
} []);

Here, we have passed the wrong url. In that case, axios will throw an error in the catch method instead of running the then() method. That way, we can capture the errors using axios also.

Conclusion

There are also many other features we can use with Axios, like working with promises using async and await. Also, it provides features like transforms(which allow you to provide functions to transform the outgoing or incoming data) and interceptors(which can be attached to fire when a request is made or when a response is received).

Suppose you want to build a ReactJS application that utilizes Axios for data fetching and handling. In that case, it may be a good idea to hire ReactJS developer who has experience working with both technologies. They can help you build a high-quality web application that meets your business needs and exceeds your users’ expectations.

Frequently Asked Questions (FAQs)

1. What is Axios?

Axios is the promised-based HTTP library that helps programmers make requests independently or as a third-party server to fetch data. Thus, it delivers several ways to create requests like GET, PUT, DELETE and POST.

2. What is the use of Axios in React?

Using Axios in react allows you to communicate with APIs simply in our React apps. Other methods, such as Fetch or AJAX, achieve it. Axos gives a little bit more functionality, which goes a long way with the React apps. Hence, Axios is the promise-based library used with a Node.

3. Why use Axios with a React query?

At remote, Axios and React query utilize to construct the “data layer” and interact with API endpoints. Combining these two libraries will easily fetch, cache and update data in React apps.


Book your appointment now

Request a Quote