All files / src/hooks use-pagination.ts

65.85% Statements 27/41
82.14% Branches 23/28
50% Functions 7/14
68.42% Lines 26/38

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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193                                                                                                                                29x     29x             29x 29x     29x   27x           29x 26x 1x 1x   1x                     1x         29x 2x 2x 1x 1x 1x           29x           29x                   29x 2x 2x     29x         29x                     29x                                                                          
import { useState, useCallback, useEffect } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import type {
  PaginationParams,
  PaginatedResult,
  PaginationMeta,
} from '@/lib/pagination';
import { getPaginationState, PAGINATION_DEFAULTS } from '@/lib/pagination';
 
// Generic pagination hook configuration
export interface UsePaginationConfig<
  T,
  TParams extends PaginationParams = PaginationParams,
> {
  queryKey: (params: TParams) => readonly unknown[];
  queryFn: (params: TParams) => Promise<PaginatedResult<T>>;
  initialParams?: Partial<TParams>;
  staleTime?: number;
  retry?: number;
}
 
// Generic pagination hook return type for load more functionality
export interface UsePaginationReturn<
  T,
  TParams extends PaginationParams = PaginationParams,
> {
  // Data
  data: T[];
  pagination: PaginationMeta;
 
  // Loading states
  isLoading: boolean;
  isLoadingMore: boolean;
  isFetching: boolean;
 
  // Error state
  error: string | null;
 
  // Pagination state
  currentPage: number;
  hasNextPage: boolean;
  totalItems: number;
  totalPages: number;
 
  // Load more functionality
  loadMore: () => void;
 
  // Utility functions
  refresh: () => void;
  reset: () => void;
  setParams: (params: Partial<TParams>) => void;
  updateData: (updater: (data: T[]) => T[]) => void;
 
  // Current parameters
  params: TParams;
}
 
/**
 * Generic pagination hook for load more functionality
 */
export function usePagination<
  T,
  TParams extends PaginationParams = PaginationParams,
>(config: UsePaginationConfig<T, TParams>): UsePaginationReturn<T, TParams> {
  const queryClient = useQueryClient();
 
  // State for current parameters
  const [params, setParamsState] = useState<TParams>({
    page: PAGINATION_DEFAULTS.page,
    pageSize: PAGINATION_DEFAULTS.pageSize,
    ...config.initialParams,
  } as TParams);
 
  // State for accumulated data (for load more functionality)
  const [accumulatedData, setAccumulatedData] = useState<T[]>([]);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
 
  // Fetch data with React Query
  const { data, isLoading, isFetching, error, refetch } = useQuery({
    queryKey: config.queryKey(params),
    queryFn: () => config.queryFn(params),
    staleTime: config.staleTime || 5 * 60 * 1000, // 5 minutes default
    retry: config.retry || 3,
  });
 
  // Update accumulated data when new data arrives
  useEffect(() => {
    if (data?.data) {
      const currentPage = params.page || 1;
      if (currentPage === 1) {
        // Reset accumulated data for first page
        setAccumulatedData(data.data);
      } else E{
        // Append new data for subsequent pages (load more functionality)
        setAccumulatedData(prev => {
          const existingIds = new Set(prev.map((item: any) => item.id));
          const newItems = data.data.filter(
            (item: any) => !existingIds.has(item.id)
          );
          return [...prev, ...newItems];
        });
      }
      setIsLoadingMore(false);
    }
  }, [data, params.page]);
 
  // Load more functionality
  const loadMore = useCallback(() => {
    const currentPage = params.page || 1;
    if (data?.pagination && currentPage < data.pagination.pageCount) {
      setIsLoadingMore(true);
      setParamsState(
        prev => ({ ...prev, page: (prev.page || 1) + 1 }) as TParams
      );
    }
  }, [data?.pagination, params.page]);
 
  // Utility functions
  const refresh = useCallback(() => {
    setAccumulatedData([]);
    setParamsState(prev => ({ ...prev, page: 1 }) as TParams);
    refetch();
  }, [refetch]);
 
  const reset = useCallback(() => {
    setParamsState({
      page: PAGINATION_DEFAULTS.page,
      pageSize: PAGINATION_DEFAULTS.pageSize,
      ...config.initialParams,
    } as TParams);
    setAccumulatedData([]);
    queryClient.invalidateQueries({ queryKey: config.queryKey(params) });
  }, [config, params, queryClient]);
 
  const setParams = useCallback((newParams: Partial<TParams>) => {
    setParamsState(prev => ({ ...prev, ...newParams, page: 1 }) as TParams);
    setAccumulatedData([]); // Reset accumulated data when params change
  }, []);
 
  const updateData = useCallback((updater: (data: T[]) => T[]) => {
    setAccumulatedData(updater);
  }, []);
 
  // Calculate pagination state
  const paginationState = data?.pagination
    ? getPaginationState(data.pagination, isLoading, isLoadingMore)
    : {
        currentPage: 1,
        hasNextPage: false,
        isLoading,
        isLoadingMore,
        totalItems: 0,
        totalPages: 0,
      };
 
  return {
    // Data
    data: accumulatedData,
    pagination: data?.pagination || {
      page: 1,
      pageSize: PAGINATION_DEFAULTS.pageSize,
      pageCount: 0,
      total: 0,
    },
 
    // Loading states
    isLoading: isLoading && (params.page || 1) === 1,
    isLoadingMore,
    isFetching,
 
    // Error state
    error: error?.message || null,
 
    // Pagination state
    currentPage: paginationState.currentPage,
    hasNextPage: paginationState.hasNextPage,
    totalItems: paginationState.totalItems,
    totalPages: paginationState.totalPages,
 
    // Load more functionality
    loadMore,
 
    // Utility functions
    refresh,
    reset,
    setParams,
    updateData,
 
    // Current parameters
    params,
  };
}