Flat Preloader Icon

Fetching Data with Axios

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 <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <h1>Data from API</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};

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 <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <h1>Data from API</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};

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.