Axios is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node.js.
Here’s how you can use Axios with React:
1. Install Axios:
You can add Axios to your project by typing the following command to your terminal if you are using npm:
```
npm install axios
```
or if you are using yarn:
```
yarn add axios
```
1. Import Axios:
Before using Axios, you have to import it first to your react component.
```
import axios from ‘axios’;
```
1. Make HTTP Requests:
Once Axios is imported to your component, you can use it to make HTTP requests (GET, POST, PUT, DELETE, etc). Let’s code a sample to fetch some data from an API:
```
import React, { useState, useEffect } from ‘react’;
import axios from ‘axios’;
function FetchData() { const [data, setData] = useState([]);
useEffect(() => { axios.get(‘https://api.example.com/items’) .then(response => { setData(response.data); }) .catch(error => { console.log(‘Error getting api data’, error); }); }, []); return (export default FetchData;
```
In the above code, we make a `GET` HTTP request to `https://api.example.com/items` and then we capture the response and use it to set our state.
You can also make POST requests using the `axios.post()` function as seen below:
```
axios.post(‘/user’, {
firstName: ‘Fred’,
lastName: ‘Flintstone‘
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```
Remember, whenever you’re making requests to an API, you should ideally handle loading and error states by using conditional rendering. You can handle the different states by having a loading state and error state in your component’s state.