API Call in React Using Axios.
Introduction
Most of the Web and Mobile apps need to communicate with server or external services to get and store data. This can be done by calling API. These apps use HTTP requests to communicate with APIs.
In react APIs can be consumed in various ways in which AXIOS and Fetch API are most popular.
In this article, we will discuss and implement Axios to access Dummy Rest API in a React application.
What is Axios?
Axios is a promise based lightweight HTTP client for browser and node.js.
Features at a glance
- Make XMLHttpRequests from browser
This gives the ability to a web page to update just a part of a page without disrupting other areas.
- Make HTTP request from node.js
As Axios works with node applications you can consume a third-party API, also this is useful in SSR(Server side rendering) for web applications.
- Promise based support
Promise-based API gives you the ability to write more readable asynchronous code by taking advantage of native async and await javascript features.
- Request and response interception
Interceptors are basically functions that Axios calls for every request and response.
You can intercept a request to transform it before Axios sends it or transform a response before Axios returns it to the caller.
- Efficient error handling
As Axios built on promises, it has then() function for promise chaining and .catch() function for error handling.
You can also use response interceptors to handle errors. Response interceptor function takes two parameters, successHandler and errorHandler. You can write your own error handler to transform errors as you want.
- Protection against CSRF
Axios supports token-based support to prevent CSRF.
- Request cancellation support
Suppose we need to cancel the request when the user navigates from the current page to another after making an API call, then this can be done in Axios by using the cancellation token.
- Automatic transformation for JSON data
Let's take a quick look at the basic usage of Axios
Using Axios to make HTTP requests is very easy.
Perform GET request
axios({
method: 'get',
url: 'https:/reqres.in/api/users?page=2'
})
Perform POST request
axios({
method: 'post',
url: 'https:/reqres.in/api/register',
data: {
email: 'test@example.com',
password: abc123
}
})
Above requests can also be made with inbuilt alias methods as
axios.get('https:/reqres.in/api/users?page=2')
axios.post('https:/reqres.in/api/register',{
email: 'test@example.com',
password: abc123
}
)
Now let's consume Dummy Rest API in a React application
Installing Axios
To install Axios run the below command in terminal
Terminal:
npm install axios --save
After installing, we need to import Axios into our application.
In our application, we will display a user list.
To Import Axios in UserList component add below line in UserList.js file
import axios from 'axios'
Now it's time to call get API, to do this write the below function and call it from useEffect hook
function GetAllUSers() {
axios.get('https://reqres.in/api/users?page=2')
.then(response => {
console.log(response.data)
const { data } = response.data
SetUserData(data)
}).catch(error => {
console.log(error);
})
}
In GetAllUsers, we are calling users API and requesting data for page no 2 and getting a response in then block. Then we are destructuring data from the response and setting it into a UserData state variable. The result will be rendered as below.
Now before making a Post request letβs take a look at how we can configure the base instance of Axios.
Create file api.js in the src folder.
Import Axios and add below code block.
export default axios.create({
baseURL: `https://reqres.in/`
});
Here we are creating and exporting a new instance of Axios with baseURL.
Like baseURL we can also configure another Axios parameter like
Header, timeout, response type, and so on.
Now let's use the same base instance for making a POST request.
Add below import statement in UserList.js component
import baseInstance from '../api'
Use this base instance for adding User. Here you can see we have just specified only the endpoint to add a user.
const AddUser = async (event) => {
event.preventDefault();
await baseInstance.post('api/users', {
name: UserName,
job: UserRole
}).then(res => {
alert(`Data saved successfully.
ID = ${res.data.id}
First name = ${res.data.name}
Role = ${res.data.job}
Created At = ${res.data.createdAt}`
)
console.log(res.data);
}).catch(error => {
console.log(error);
});
}
Also, you can see how we are using async and await with Axios.
Conclusion
In this article, we have used Axios to make HTTP requests in react applications.
The complete source for this article is available here on github.
Top comments (5)
Fetch is now supported everywhere, you can replace axios with fetch
Ok. I will try it.
How can I pass header in request?
The title of this article is "use axios with react". Where is the "with react" part?
After features of axios, I have given example of Get and Post request with react.