Flat Preloader Icon

Handling API Requests

Handling API requests in a React application involves several steps to ensure data is fetched, processed, and displayed correctly, while also managing loading states and errors effectively.

1. Set Up Your React Application

If you haven’t already, set up a React application. You can use Create React App for a quick setup:
				
					npx create-react-app my-app
cd my-app
npm start

				
			

2. Install Axios

				
					npm install axios

				
			

3. Create an API Service

Create a dedicated service file to handle your API requests. This keeps your code modular and easy to maintain. 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 and manage the component state based on the request status.
				
					// 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. Handling Authentication

If the API requires authentication, include the necessary headers. For example, if an API key is required:
				
					// src/apiService.js
import axios from 'axios';

const API_URL = 'https://api.example.com';
const API_KEY = 'your-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;
  }
};

				
			

6. Store Sensitive Information in Environment Variables

  • Store sensitive information like API keys in environment variables. Create a .env file in the root of your project.
  • Access these variables in your code using process.env:

7. Manage Loading and Error States

Ensure your application handles loading and error states gracefully. This improves the user experience by providing feedback during data fetching and when errors occur.

8. Example with Complete Error Handling

Here’s a complete example demonstrating how to handle API requests, including loading and error states, and optional authentication:
				
					// 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;