JAVASCRIPT

useFetch for declarative data fetching

A reusable React hook for declaratively fetching data from an API, managing loading, error, and data states efficiently in your components.

import { useState, useEffect } from 'react';

  function useFetch(url) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
      const abortController = new AbortController();
      const signal = abortController.signal;

      const fetchData = async () => {
        setLoading(true);
        setError(null);
        try {
          const response = await fetch(url, { signal });
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          const json = await response.json();
          setData(json);
        } catch (err) {
          if (err.name === 'AbortError') {
            console.log('Fetch aborted');
          } else {
            setError(err);
          }
        } finally {
          setLoading(false);
        }
      };

      fetchData();

      return () => {
        abortController.abort();
      };
    }, [url]);

    return { data, loading, error };
  }

  // Example Usage:
  // function MyComponent() {
  //   const { data, loading, error } = useFetch('https://api.example.com/items');

  //   if (loading) return <div>Loading...</div>;
  //   if (error) return <div>Error: {error.message}</div>;
  //   if (!data) return null;

  //   return (
  //     <div>
  //       <h1>Items</h1>
  //       <ul>
  //         {data.map(item => (
  //           <li key={item.id}>{item.name}</li>
  //         ))}
  //       </ul>
  //     </div>
  //   );
  // }
How it works: The `useFetch` hook encapsulates the logic for data fetching, including managing loading, error, and data states. It takes a URL as an argument and returns an object containing the current `data`, `loading` status, and any `error`. The `useEffect` hook handles the asynchronous fetch operation and its cleanup, ensuring that pending requests are aborted when the component unmounts or the URL changes. This promotes reusability and cleaner component code by centralizing data fetching concerns.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs