Blog>
Snippets

Using Custom Hooks for Data Fetching

Demonstrate how to create a custom hook in TypeScript for fetching data from an API and how to use it within a React component.
import { useState, useEffect } from 'react';
import axios from 'axios';

export const useFetchData = (url: string) => {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get(url);
        setData(response.data);
      } catch (error) {
        setError(error);
      } finally {
        setIsLoading(false);
      }
    };
    fetchData();
  }, [url]);

  return { data, isLoading, error };
};
This custom hook (useFetchData) is for fetching data from an API. It takes a URL as its argument, uses Axios for the data fetch inside a useEffect hook to make the API call when the component mounts or when the URL changes. The hook maintains state for the data returned, a loading state, and any errors encountered during the fetch.
import React from 'react';
import { useFetchData } from './useFetchData';

const DataFetchingComponent = ({ url }) => {
  const { data, isLoading, error } = useFetchData(url);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

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

export default DataFetchingComponent;
This React component (DataFetchingComponent) demonstrates how to use the custom 'useFetchData' hook within a functional component. It accepts a 'url' prop for the API endpoint, then uses the hook to fetch data, handling loading and error states appropriately. The fetched data (if available) is rendered as pretty-printed JSON.