react.useEffect for API handling

react.useEffect for API handling

In React, the useEffect hook helps manage extra tasks in functional components. It's often used for things like getting data, subscriptions, or changing the DOM. For working with APIs, useEffect is great for starting tasks that take time, like getting data through HTTP requests.

Here's an example of how you might use useEffect for API handling in a React functional component:

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

const MyComponent = () => {
  // State to store the fetched data
  const [data, setData] = useState(null);

  // State to handle loading and error states
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // The URL of the API you want to fetch data from
  const apiUrl = 'https://api.example.com/data';

  useEffect(() => {
    // Function to fetch data from the API
    const fetchData = async () => {
      try {
        // Set loading state to true while fetching data
        setLoading(true);

        // Make the API request
        const response = await fetch(apiUrl);

        // Check if the request was successful
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }

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

        // Set the data state with the fetched data
        setData(result);

        // Set loading state to false after successfully fetching data
        setLoading(false);
      } catch (error) {
        // If an error occurs during the fetch, set the error state
        setError(error);

        // Set loading state to false
        setLoading(false);
      }
    };

    // Call the fetchData function when the component mounts
    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // The empty dependency array means this effect will only run once, similar to componentDidMount

  // Render the component based on the loading and error states
  if (loading) {
    return <p>Loading...</p>;
  }

  if (error) {
    return <p>Error: {error.message}</p>;
  }

  // Render the component with the fetched data
  return (
    <div>
      <h1>MyComponent</h1>
      <p>Data: {JSON.stringify(data)}</p>
    </div>
  );
};

export default MyComponent;

In this example:

  1. In this example, the useEffect hook starts the data fetching process when the component is first shown (like componentDidMount in class components).

  2. In the useEffect callback, we create an async function (fetchData) to manage the API request. This function sets the loading state to true, makes the API request, and then changes the state depending on whether the request succeeds or fails.

  3. The useEffect hook uses an empty dependency array ([]). This makes it run only one time when the component mounts. This way, the API request happens just once.

  4. The component shows different things based on loading and error states. If data is loading, it shows a loading message. If there's an error during fetching, it shows an error message. If data is fetched successfully, it displays the component with the fetched data.