All files / src/features/dashboard/hooks use-dashboard-data.ts

100% Statements 18/18
100% Branches 3/3
100% Functions 4/4
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49                        40x 40x 40x   40x 22x 22x 22x 22x 17x     5x 5x 5x   22x         40x 4x     40x 18x     40x              
import { useState, useEffect, useCallback } from 'react';
import type { DashboardHookReturn } from '../components/shared/dashboard-types';
 
/**
 * Custom hook for handling async data fetching with standardized loading/error states
 * Used across dashboard components to eliminate duplicate state management logic
 */
export function useDashboardData<T>(
  fetchFunction: () => Promise<T>,
  initialData: T,
  dependencies: any[] = []
): DashboardHookReturn<T> {
  const [data, setData] = useState<T>(initialData);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
 
  const loadData = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const result = await fetchFunction();
      setData(result);
    } catch (err) {
      const errorMessage =
        err instanceof Error ? err.message : 'An unknown error occurred';
      setError(errorMessage);
      console.error('Dashboard data loading error:', err);
    } finally {
      setLoading(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fetchFunction, ...dependencies]);
 
  const refetch = useCallback(async () => {
    await loadData();
  }, [loadData]);
 
  useEffect(() => {
    loadData();
  }, [loadData]);
 
  return {
    data,
    loading,
    error,
    refetch,
  };
}