All files / src/hooks/useUserManagement useUserList.ts

100% Statements 10/10
100% Branches 5/5
100% Functions 4/4
100% Lines 10/10

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                                      23x             149x     149x   149x   55x               149x 3x 2x           1x                         149x          
/**
 * useUserList Hook
 *
 * React Query hook for fetching paginated user list with filters.
 * Story 2.5.2: User Management Frontend
 */
 
import { useQuery, useQueryClient, keepPreviousData } from '@tanstack/react-query';
import type { UserFilters, UserPagination } from '@/types/user.types';
import { listUsers } from '@/services/api/userManagementApi';
 
interface UseUserListOptions {
  filters: UserFilters;
  pagination: UserPagination;
  sortBy?: string;
  sortDir?: 'asc' | 'desc';
  enabled?: boolean;
}
 
export const useUserList = ({
  filters,
  pagination,
  sortBy,
  sortDir,
  enabled = true,
}: UseUserListOptions) => {
  const queryClient = useQueryClient();
 
  // Extract only the properties that affect the API call for the query key
  const { page, limit } = pagination;
 
  const query = useQuery({
    queryKey: ['users', 'list', { filters, page, limit, sortBy, sortDir }],
    queryFn: () => listUsers(filters, pagination, undefined, sortBy, sortDir),
    staleTime: 5 * 60 * 1000, // 5 minutes
    gcTime: 30 * 60 * 1000, // 30 minutes (formerly cacheTime)
    placeholderData: keepPreviousData, // Keep previous data during refetch (prevents "page reload" effect)
    enabled,
  });
 
  // Prefetch next page in background
  const prefetchNextPage = () => {
    if (pagination.hasNext && pagination.page) {
      queryClient.prefetchQuery({
        queryKey: [
          'users',
          'list',
          { filters, page: pagination.page + 1, limit: pagination.limit, sortBy, sortDir },
        ],
        queryFn: () =>
          listUsers(
            filters,
            { ...pagination, page: pagination.page! + 1 },
            undefined,
            sortBy,
            sortDir
          ),
        staleTime: 5 * 60 * 1000,
      });
    }
  };
 
  return {
    ...query,
    prefetchNextPage,
  };
};