import { useEffect, useState } from 'react';

type UseTableDataProps<T> = {
  fetchData: () => Promise<T[]>;
};

type UseTableDataResult<T> = {
  data: T[];
  loading: boolean;
  error: string | null;
};

export const useTableData = <T,>({
  fetchData,
}: UseTableDataProps<T>): UseTableDataResult<T> => {
  const [data, setData] = useState<T[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      setError(null);
      try {
        const responseData = await fetchData();
        setData(responseData);
      } catch (error) {
        console.error(error);
        setError('Error fetching data');
      }
      setLoading(false);
    };

    loadData();
  }, []);

  return { data, loading, error };
};
