update table component

This commit is contained in:
Alexander Navarro 2023-09-16 12:46:23 -03:00
parent 176279ecb5
commit 41d682e9df
4 changed files with 167 additions and 28 deletions

View 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),
};
}