Files
vibemake-admin/src/utils/usePaged.ts
T
2026-10-27 14:07:44 +08:00

72 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useCallback, useEffect, useRef, useState } from 'react';
import { App } from 'antd';
import type { PageResponse } from '@/api/types';
import { errorText } from './format';
/** 通用分页列表 hook:fetcher 接收 page/size 与筛选条件 */
export function usePaged<T, Q extends object>(
fetcher: (q: Q & { page: number; size: number }) => Promise<PageResponse<T>>,
initialQuery: Q,
deps: unknown[] = [],
) {
const { message } = App.useApp();
const [query, setQuery] = useState<Q>(initialQuery);
const [page, setPage] = useState(1);
const [size, setSize] = useState(20);
const [data, setData] = useState<PageResponse<T>>({ items: [], page: 1, size: 20, total: 0 });
const [loading, setLoading] = useState(false);
const fetcherRef = useRef(fetcher);
fetcherRef.current = fetcher;
const reload = useCallback(async () => {
setLoading(true);
try {
setData(await fetcherRef.current({ ...query, page, size }));
} catch (e) {
const t = errorText(e);
if (t) message.error(t);
} finally {
setLoading(false);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [query, page, size, ...deps]);
useEffect(() => {
reload();
}, [reload]);
const search = (q: Q) => {
setPage(1);
setQuery(q);
};
return {
data,
loading,
reload,
search,
query,
pagination: {
current: page,
pageSize: size,
total: data.total,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50, 100],
showTotal: (t: number) => `共 ${t} 条`,
onChange: (p: number, s: number) => {
setPage(s !== size ? 1 : p);
setSize(s);
},
},
};
}
/** 去掉空字符串/undefined,避免发送 role= 等空枚举 */
export function clean<T extends object>(v: T): T {
const out: Record<string, unknown> = {};
for (const [k, val] of Object.entries(v)) {
if (val !== undefined && val !== null && val !== '') out[k] = typeof val === 'string' ? val.trim() : val;
}
return out as T;
}