update table component
This commit is contained in:
parent
176279ecb5
commit
41d682e9df
4 changed files with 167 additions and 28 deletions
90
src/hooks/usePagination.tsx
Normal file
90
src/hooks/usePagination.tsx
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
import { useReducer } from 'react';
|
||||
|
||||
export interface IUsePagination<T> {
|
||||
items: T[];
|
||||
changeOffset: (offset: Offset) => void;
|
||||
}
|
||||
|
||||
interface Props<T> {
|
||||
items: T[];
|
||||
}
|
||||
|
||||
interface State {
|
||||
offset: number;
|
||||
total: number;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
type ActionType =
|
||||
| { type: 'update'; value: any; name: string }
|
||||
| { type: 'update'; value: any; name: string };
|
||||
|
||||
export enum Offset {
|
||||
Next,
|
||||
Prev,
|
||||
First,
|
||||
Last,
|
||||
}
|
||||
|
||||
export default function usePagination<T>({
|
||||
items,
|
||||
}: Props<T>): IUsePagination<T> {
|
||||
const reducer = (state: State, action: ActionType): State => {
|
||||
switch (action.type) {
|
||||
case 'update':
|
||||
return {
|
||||
...state,
|
||||
[action.name]: action.value,
|
||||
};
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
};
|
||||
|
||||
const [state, dispatch] = useReducer(reducer, {
|
||||
offset: 0,
|
||||
total: 0,
|
||||
limit: 30,
|
||||
});
|
||||
|
||||
const changeOffset = (offset: Offset): void => {
|
||||
switch (offset) {
|
||||
case Offset.Next:
|
||||
dispatch({
|
||||
type: 'update',
|
||||
name: 'offset',
|
||||
value: state.offset + state.limit,
|
||||
});
|
||||
break;
|
||||
case Offset.Prev:
|
||||
dispatch({
|
||||
type: 'update',
|
||||
name: 'offset',
|
||||
value: state.offset - state.limit,
|
||||
});
|
||||
break;
|
||||
case Offset.First:
|
||||
dispatch({
|
||||
type: 'update',
|
||||
name: 'offset',
|
||||
value: 0,
|
||||
});
|
||||
break;
|
||||
case Offset.Last:
|
||||
dispatch({
|
||||
type: 'update',
|
||||
name: 'offset',
|
||||
value: items.length - state.limit,
|
||||
});
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
changeOffset,
|
||||
items: items.slice(state.offset, state.offset + state.limit),
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue