Axios with React Hooks, “traditional” Promise syntax
Using Axios with React Hooks and Traditional Promise Syntax
If you're developing a React application, you may need to make API calls to retrieve data. Axios is a popular library used for making HTTP requests, and React Hooks allow you to use state and other React features without writing a class.
Using Axios with React Hooks
To use Axios with React Hooks, you need to install the Axios package:
npm install axios
Then, you can import Axios and use it in a functional component:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function MyComponent() {
const [data, setData] = useState([]);
useEffect(() => {
axios.get('/api/data')
.then(response => setData(response.data))
.catch(error => console.error(error));
}, []);
return (
<ul>
{data.map(item => (<li key={item.id}>{item.name}</li>))}
</ul>
);
}
export default MyComponent;
In this example, the useState
hook is used to initialize the data
state as an empty array. The useEffect
hook is used to make an API call to retrieve data from the /api/data
endpoint. When the component mounts, the useEffect
hook runs and makes the API call using Axios. If the API call is successful, the response data is stored in the data
state using the setData
function. If the API call fails, the error is logged to the console.
Using Traditional Promise Syntax with Axios
If you prefer to use traditional Promise syntax instead of React Hooks, you can use Axios in a similar way:
import axios from 'axios';
axios.get('/api/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
In this example, the axios.get
function is called to make an API call to retrieve data from the /api/data
endpoint. If the API call is successful, the response data is logged to the console. If the API call fails, the error is logged to the console.
Overall, using Axios with React Hooks or traditional Promise syntax can help simplify making API calls in your React application.