usePagedExporter.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. export interface PagedExporterOptions<TParams> {
  2. pageSize?: number;
  3. request: (params: TParams & { current: number; pageSize: number }) => Promise<{ data: any[]; total: number } | undefined>;
  4. }
  5. export interface PagedExporterResult {
  6. fetchData: () => Promise<{ currentCount: number; totalCount: number }>;
  7. reset: () => void;
  8. getAll: () => any[];
  9. }
  10. // 可复用的分页导出 Hook(无 React 依赖,简单状态机)
  11. export function createPagedExporter<TParams = any>(options: PagedExporterOptions<TParams>) {
  12. const state = {
  13. current: 0,
  14. totalData: [] as any[],
  15. pageSize: options.pageSize || 100,
  16. };
  17. const fetchData = async (passThroughParams: TParams): Promise<{ currentCount: number; totalCount: number }> => {
  18. state.current += 1;
  19. const resp = await options.request({ ...(passThroughParams as any), current: state.current, pageSize: state.pageSize });
  20. const total = resp?.total || 0;
  21. const data = resp?.data || [];
  22. state.totalData = [...state.totalData, ...data];
  23. return { currentCount: state.totalData.length, totalCount: total };
  24. };
  25. const reset = () => {
  26. state.current = 0;
  27. state.totalData = [];
  28. };
  29. const getAll = () => state.totalData;
  30. return { fetchData, reset, getAll } as const;
  31. }