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

50 lines
1.8 KiB
TypeScript

import { commonCodeApi } from "@/lib/api/commonCode";
import { queryKeys } from "@/lib/queryKeys";
import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";
import type { CodeFilter } from "@/lib/schemas/commonCode";
import type { CodeInfo } from "@/types/commonCode";
/**
* 코드 목록 무한 스크롤 훅
* 카테고리별로 코드 목록을 무한 스크롤로 로드
*/
export function useCodesInfinite(categoryCode: string, filters?: CodeFilter) {
return useInfiniteScroll<CodeInfo, CodeFilter>({
queryKey: queryKeys.codes.infiniteList(categoryCode, filters),
queryFn: async ({ pageParam, ...params }) => {
// 첫 페이지는 20개, 이후는 10개씩
const pageSize = pageParam === 1 ? 20 : 10;
const response = await commonCodeApi.codes.getList(categoryCode, {
...params,
page: pageParam,
size: pageSize,
});
return {
data: response.data || [],
total: response.total,
currentPage: pageParam,
pageSize: pageSize,
};
},
initialPageParam: 1,
pageSize: 20, // 첫 페이지 기준
params: filters,
staleTime: 5 * 60 * 1000, // 5분 캐싱
enabled: !!categoryCode, // categoryCode가 있을 때만 실행
// 커스텀 getNextPageParam 제공
getNextPageParam: (lastPage, allPages, lastPageParam) => {
// 마지막 페이지의 데이터 개수가 요청한 페이지 크기보다 작으면 더 이상 페이지 없음
const currentPageSize = lastPageParam === 1 ? 20 : 10;
const dataLength = lastPage.data?.length || 0;
// 받은 데이터가 요청한 크기보다 작으면 마지막 페이지
if (dataLength < currentPageSize) {
return undefined;
}
return lastPageParam + 1;
},
});
}