DEV Community

Cover image for Working with Axios in React
Cesare Ferrari
Cesare Ferrari

Posted on

Axios React Working with Axios in React

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
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

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))
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
lovmo profile image
Vetle Endresen

Hi, nice article! A question, where should API requests live within a React app? Say you have a database with many models, and you want to perform CRUD on them. Should you call the relevant API's from each component?