Understanding Axios and using with React to Make API Requests

About Axios

Brham Dev Mahato
2 min readMay 12, 2020

Axios is a Promise-based JavaScript HTTP client library used to make HTTP requests from the browser that allows us to interact with REST API.

So we can use Axios with React to make requests to an API, return data from the API, and then do stuff in our React app with that data.

Importance of Axios

The best thing about Axios is that it lets us interact easily with APIs in our React apps.

API allows apps to retrieve or send data to and from databases or web services. Apps use HTTP requests, for example, GET, POST, and PUT, to communicate with APIs. In short, Axios makes it easy for our apps to perform these commands.

Axios is promise-based and thus we can take advantage of async and await for more readable asynchronous code.

Available shorthand methods in Axios

  • Axios.get(url[, config])
  • Axios.request(config)
  • Axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

Installing the Axios Client

Now let’s install Axios in our React project using the following command from your project’s root folder:

$ npm install axios

Getting API data with Axios

Open the src/components/UsersList.js file from React app and import the Axios library, define the URL variable that holds the URL of our third-party REST API and add a state variable that will be used to hold users after getting them from the REST API.

Next, let’s add a componentDidMount() life-cycle hook in our UserList component; and then add the code required to send a GET request to fetch the JSON data from the API. Then import the UsersList component to App.js file to display the name list of users.

users list component
App component

Conclusion

We have reached the end of our tutorial where we learned how to use Axios with React and to fetch and display JSON data from a RESTful API. Similarly, we can use Axios for Post and Delete data.

--

--