ahooks
Version:
react hooks library
45 lines (44 loc) • 1.94 kB
JavaScript
import { __rest } from "tslib";
import { useMemo } from 'react';
import useMemoizedFn from '../useMemoizedFn';
import useRequest from '../useRequest';
const usePagination = (service, options = {}) => {
var _a;
const { defaultPageSize = 10, defaultCurrent = 1 } = options, rest = __rest(options, ["defaultPageSize", "defaultCurrent"]);
const result = useRequest(service, Object.assign({ defaultParams: [{ current: defaultCurrent, pageSize: defaultPageSize }], refreshDepsAction: () => {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
changeCurrent(1);
} }, rest));
const { current = 1, pageSize = defaultPageSize } = result.params[0] || {};
const total = ((_a = result.data) === null || _a === void 0 ? void 0 : _a.total) || 0;
const totalPage = useMemo(() => Math.ceil(total / pageSize), [pageSize, total]);
const onChange = (c, p) => {
let toCurrent = c <= 0 ? 1 : c;
const toPageSize = p <= 0 ? 1 : p;
const tempTotalPage = Math.ceil(total / toPageSize);
if (toCurrent > tempTotalPage) {
toCurrent = Math.max(1, tempTotalPage);
}
const [oldPaginationParams = {}, ...restParams] = result.params || [];
result.run(...[
Object.assign(Object.assign({}, oldPaginationParams), { current: toCurrent, pageSize: toPageSize }),
...restParams,
]);
};
const changeCurrent = (c) => {
onChange(c, pageSize);
};
const changePageSize = (p) => {
onChange(current, p);
};
return Object.assign(Object.assign({}, result), { pagination: {
current,
pageSize,
total,
totalPage,
onChange: useMemoizedFn(onChange),
changeCurrent: useMemoizedFn(changeCurrent),
changePageSize: useMemoizedFn(changePageSize),
} });
};
export default usePagination;