ERP-node/frontend/hooks/queries/useCategoriesInfinite.ts

43 lines
1.6 KiB
TypeScript

import { commonCodeApi } from "@/lib/api/commonCode";
import { queryKeys } from "@/lib/queryKeys";
import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";
import type { CategoryFilter } from "@/lib/schemas/commonCode";
import type { CodeCategory } from "@/types/commonCode";
/**
* 카테고리 무한 스크롤 훅
*/
export function useCategoriesInfinite(filters?: CategoryFilter) {
return useInfiniteScroll<CodeCategory, CategoryFilter>({
queryKey: queryKeys.categories.infinite(filters),
queryFn: async ({ pageParam, ...params }) => {
// API 호출 시 페이지 정보 포함
const expectedSize = pageParam === 1 ? 20 : 10; // 첫 페이지는 20개, 이후는 10개씩
const response = await commonCodeApi.categories.getList({
...params,
page: pageParam,
size: expectedSize,
});
return {
data: response.data || [],
total: response.total,
hasMore: (response.data?.length || 0) >= expectedSize, // 예상 크기와 같거나 크면 더 있을 수 있음
};
},
initialPageParam: 1,
pageSize: 20, // 첫 페이지 기준
params: filters,
staleTime: 5 * 60 * 1000, // 5분 캐싱
// 커스텀 getNextPageParam 제공
getNextPageParam: (lastPage, allPages, lastPageParam) => {
// 마지막 페이지의 데이터 개수가 요청한 크기보다 작으면 더 이상 페이지 없음
const expectedSize = lastPageParam === 1 ? 20 : 10;
if ((lastPage.data?.length || 0) < expectedSize) {
return undefined;
}
return lastPageParam + 1;
},
});
}