5 steps to make a simple request using Axios in React

Tags: react, npm
Published: 2020-08-05 14:56:09

If you started to develop an application on React, you probably have to connect your front-end with a server. Usually, this communication occurs with an HTTP protocol. 

There are many ways to retrieve, post or modify data from a server; you can use Fetch API, XMLHttpRequest or multiple libraries. 

Axios is a lightweight NPM library similar to Fetch API, the pack provides an easy way to use REST API and make requests. In this article, I will show in 5 steps how to use Axios in your React application.

### 1. Install it in your project

We can start by adding Axios to our project. Open your terminal and go to the root of your project — where the package.json is — Then install the pack. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1ogbij4nnbcwf27z18f4.png)

### 2.Create a service folder

Once you have Axios install, it is essential to decide which folder the API requests will be. Separating your request is a good way to keep your code clean and refactored. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rbl2nhf8nanpbu56subn.png)

### 3.	Build your function

In this next step, we will finally start to write some code. First, import the library on the top of your JavaScript file. 

`import axios from 'axios'`

Now you can start to write your function. Remember to choose a name that makes sense of what do you expect from this function. 

```javascript 
function fetchFilmsApi (){
} 
```

Axios is promise-based; for this reason, we can make use of async and wait to create nice and asynchronous code. We will transform our function in an async function and create a variable to store the response of our request. 

```javascript 
async function fetchFilmsApi (){
 const response = await axios.get(insertUrl)// insert the API url
} 
```

Now we have to create a return that provides us with the data of our response. Do not forget to export your function! 

```javascript 
export default async function fetchFilmsApi (){
 const response = await axios.get(insertUrl)// insert the API url
 return  response.data

} 
```

### 4.Import the function 

Our function is done, now we have to build our main component — where the data will be used. There we will import our API function. 

`import fetchFilmsApi from "../../services/api"`

### 5. Handle the response

Once we have our HTTP request done, Axios will return for us a promise with a successful or failure response. To handle the result, we will use two methods then() and catch(). 

```javascript 
 getData =()=> {
        this.fetchFilmsApi().then().catch()
    }
 
```

If the response is fulfilled, then() will be called and inside the method, we will decide what to do with the data. In our case, we are assigning it to a state. 

```javascript 
 getData =()=> {
        this.fetchFilmsApi().then(res=> this.setState({data:res}).catch()
    }
 
```

In case the promise is not fulfilled, catch() will be called. We can log the response to understand which errors are happening.  

```javascript 
 getData =()=> {
        this.fetchFilmsApi().then(res=> this.setState({data:res}).catch(err=> console.log(`Something went wrong. ERROR: ${err}´))
    }
 ```

###Wrapping up
As you could see, for a simple request Axios take less time and effort to retrieve data, besides that, the library is supported for old browsers and transform JSON data in its background. There are many other aspects that I didn`t discuss, and you can check it all in <a href="https://github.com/axios/axios">Axios GitHub page </a>.