Fetching data with Axios in a React application is straightforward and convenient, thanks to Axios’ promise-based HTTP client.
Here’s a step-by-step guide to fetching data using Axios:
1. Set Up Your React Application
First, make sure you have a React application set up. You can use Create React App for quick setup:
npx create-react-app my-app
cd my-app
npm start
2. Install Axios
Install Axios using npm or yarn:
npm install axios
3. Create a Service to Handle API Requests
Create a dedicated file to handle API requests, which helps keep your code organized. For example, create a file apiService.js in the src directory:
// src/apiService.js
import axios from 'axios';
const API_URL = 'https://api.example.com';
export const fetchData = async () => {
try {
const response = await axios.get(`${API_URL}/endpoint`);
return response.data;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
};
4. Use the API Service in Your React Component
In your React component, use the service to fetch data. For example, in App.js:
// src/App.js
import React, { useEffect, useState } from 'react';
import { fetchData } from './apiService';
const App = () => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const getData = async () => {
try {
const result = await fetchData();
setData(result);
setLoading(false);
} catch (error) {
setError(error);
setLoading(false);
}
};
getData();
}, []);
if (loading) return Loading...
;
if (error) return Error: {error.message}
;
return (
Data from API
{JSON.stringify(data, null, 2)}
);
};
export default App;
5. Environment Variables
Store sensitive information like API keys in environment variables. Create a .env file in the root of your project:
Here’s the complete example with environment variables:
// src/apiService.js
import axios from 'axios';
const API_URL = 'https://api.example.com';
const API_KEY = process.env.REACT_APP_API_KEY;
export const fetchData = async () => {
try {
const response = await axios.get(`${API_URL}/endpoint`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
return response.data;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
};
// src/App.js
import React, { useEffect, useState } from 'react';
import { fetchData } from './apiService';
const App = () => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const getData = async () => {
try {
const result = await fetchData();
setData(result);
setLoading(false);
} catch (error) {
setError(error);
setLoading(false);
}
};
getData();
}, []);
if (loading) return Loading...
;
if (error) return Error: {error.message}
;
return (
Data from API
{JSON.stringify(data, null, 2)}
);
};
export default App;
This example demonstrates how to fetch data using Axios in a React application, including handling loading states, errors, and optionally, API authentication. This approach can be expanded to handle more complex data fetching and processing requirements as needed.