loading...
Cover image for Working with Axios in React

Working with Axios in React

cesareferrari profile image Cesare Ferrari 惻2 min read

Axios is a library that helps us make http requests to external resources

In our React applications we often need to retrieve data from external APIs so it can be displayed in our web pages.
One way to build this feature is to use the Javascript Fetch API. Fetch is quite capable of retrieving external data, but it has some limitations.

A more popular way of performing this operation is to use the Axios library. Axios is designed to handle http requests and responses.
It's used more often than Fetch because it has a larger set of features and it supports older browsers.

Axios deals with responses using Promises, so it's streamlined and easy to use in our code. Axios uses methods like get() and post() that perform http GET and POST requests for retrieving or creating resources.

We install Axios in our project in the usual way, with the npm command:

npm install axios

We have seen before that the best way to load external data in a React component is to do it inside the componentDidMount() function that gets executed right after our component has mounted.
After we retrieve the data, we typically add it to the state, so it's ready to be used by our application.

A get request

Here's the basic syntax for a GET request for a resource:

axios.get('http://localhost:3333/items')

We use the get() method and we pass in the URL where the resource lives.
Axios does its magic and returns us back a promise.
If the promise is successful, it's passed to the then() method where we use it to set state.
If the promise is not successful we get back an error that is passed to the catch() method where we can display it on the console or in some other fashion.
Here's the full call to Axios inside componentDidMount():

componentDidMount() {
  axios.get('http://localhost:3333/items')
    .then(response => this.setState({items: response.data}))
    .catch(err => console.log(err))
}

In our case, the items we requested live in the response.data array, so we update the state of our application with it.

As you can see, it's very easy to work with external data inside our React application. All we have to do is make a quick call to Axios.


I write daily about web development. If you like this article, feel free to share it with your friends and colleagues.

You can receive articles like this in your inbox by subscribing to my newsletter.

Posted on by:

cesareferrari profile

Cesare Ferrari

@cesareferrari

I write daily about front-end and back-end web development.

Discussion

markdown guide