Performing HTTP requests - anastasiamexa/react-complete-guide-course-resources GitHub Wiki

Performing HTTP requests in React often involves using the fetch API or a third-party library. Here is a basic example using the fetch API and incorporating the three commonly used states (isFetching, apiData, and error) with the help of useState in a functional component.

Assuming you want to fetch data from an API, you can structure your component as follows:

import React, { useState, useEffect } from 'react';

const MyComponent = () => {
  const [isFetching, setIsFetching] = useState(false);
  const [apiData, setApiData] = useState([]);
  const [error, setError] = useState();

  useEffect(() => {
    const fetchData = async () => {
      setIsFetching(true);

      try {
        // Perform the HTTP request
        const response = await fetch('https://api.example.com/data');
        
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }

        // Parse the response JSON
        const data = await response.json();

        // Update the state with the fetched data
        setApiData(data);
        setError(null);
      } catch (error) {
        // Handle errors
        setError(error.message);
        setApiData([]);
      } finally {
        setIsFetching(false);
      }
    };

    // Call the fetchData function
    fetchData();
  }, []); // The empty dependency array ensures that the effect runs only once after the initial render

  return (
    <div>
      {isFetching && <p>Loading...</p>}
      {error && <p>Error: {error}</p>}
      {apiData.length > 0 && (
        <ul>
          {apiData.map(item => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default MyComponent;

In this example:

  • The useEffect hook is used to initiate the data fetching when the component mounts. The empty dependency array ([]) ensures that the effect runs only once after the initial render.
  • The isFetching state is set to true before the HTTP request is made and set back to false once the request is complete.
  • The apiData state is updated with the fetched data when the request is successful.
  • The error state is set if an error occurs during the HTTP request, and it is displayed in the component.

This example assumes a basic understanding of React hooks and the fetch API. Depending on your project requirements, you might consider using a third-party library like Axios for more advanced features and better handling of HTTP requests.

⚠️ **GitHub.com Fallback** ⚠️