Axios — API Integration in Reactjs with hooks
To fetch data from a REST API, we send the AJAX request to server through some protocol, to get the requested response. There are different ways of doing this, by basic way of creating a XHRequest as well.
Few of the other ways are:
2. axios
3. superagent
In this article, we will discuss Axios.
Axios is a Promise-based HTTP client for JavaScript which can be used in your front-end application and node.js. It makes it easy to send HTTP requests to the server, to perform CRUD operations.
Features of Axios :
Axios supports operations in a variety of ways and provides so many features to make an easy task for developers to use this library.
Features
- Make XMLHttpRequests from the browser
- Make http requests from node.js
- Supports the Promise API
- Intercept request and response
- Transform request and response data
- Cancel requests
- Automatic transforms for JSON data
- Client side support for protecting against XSRF
- Better error handling
Axios methods to support http protocol
- axios.request(config)
2. axios.get(url[, config])
3. axios.delete(url[, config])
4. axios.head(url[, config])
5. axios.options(url[, config])
6. axios.post(url[, data[, config]])
7. axios.put(url[, data[, config]])
What will we build using Axios?
We will perform CRUD operation on a table using reactjs javascript library for UI. We will integrate Axios with react to fetch and transform table.
Getting started with Axios

Installing
Using npm:
$ npm install
Using bower:
$ bower install axios
Using yarn:
$ yarn add axios
Using cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Then use the Axios in react component
import axios from ‘axios’;
Then we can use it depends on our requirements.
For initial load, we put the Axios calls in the componentDidMount method of react component lifecycle, which executes just after the render method. We can also use react hooks for Axios call.
Sample call for Axios :

In above structure, we call one of the operation, then there is callback function to handle the response data. If any error occurs, it is being executed in catch block. It also has finally block, which got executed in both the cases.
Structure of response object might help you to use the required information from response object.
- data — the payload returned from the server
2. status — the HTTP code returned from the server
3. statusText — the HTTP status message returned by the server
4. headers — headers sent by server
5. config — the original request configuration
6. request — the request object
status and statusText of response object can be used to handle the response in variety of ways.

Why Axios ???

Reference to give it a try for CRUD.
https://github.com/kavitagupta972/learn-react/tree/master/axios-demo
Hope this article adds knowledge to your dictionary. Connect with me for any query.
Comments
Post a Comment