feat: add server-side table sorting
This commit is contained in:
@@ -38,6 +38,8 @@ export interface DataTableProps<TData, TValue> {
|
||||
onPageChange: (newSkip: number) => void;
|
||||
onLimitChange: (newLimit: number) => void;
|
||||
};
|
||||
sorting?: SortingState;
|
||||
onSortingChange?: (sorting: SortingState) => void;
|
||||
}
|
||||
|
||||
export function DataTable<TData, TValue>({
|
||||
@@ -53,9 +55,24 @@ export function DataTable<TData, TValue>({
|
||||
emptyTitle = 'No results found.',
|
||||
emptyDescription = 'Try adjusting your filters or search terms.',
|
||||
pagination,
|
||||
sorting: controlledSorting,
|
||||
onSortingChange,
|
||||
}: DataTableProps<TData, TValue>) {
|
||||
const [rowSelection, setRowSelection] = React.useState({});
|
||||
const [sorting, setSorting] = React.useState<SortingState>([]);
|
||||
const [internalSorting, setInternalSorting] = React.useState<SortingState>([]);
|
||||
const sorting = controlledSorting ?? internalSorting;
|
||||
const isManualSorting = Boolean(onSortingChange);
|
||||
const handleSortingChange = React.useCallback(
|
||||
(updater: SortingState | ((old: SortingState) => SortingState)) => {
|
||||
const nextSorting = typeof updater === 'function' ? updater(sorting) : updater;
|
||||
if (onSortingChange) {
|
||||
onSortingChange(nextSorting);
|
||||
return;
|
||||
}
|
||||
setInternalSorting(nextSorting);
|
||||
},
|
||||
[onSortingChange, sorting],
|
||||
);
|
||||
|
||||
const columns = React.useMemo(() => {
|
||||
const cols: ColumnDef<TData, TValue>[] = [...initialColumns];
|
||||
@@ -105,10 +122,11 @@ export function DataTable<TData, TValue>({
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onSortingChange: handleSortingChange,
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getPaginationRowModel: getPaginationRowModel(),
|
||||
manualPagination: !!pagination,
|
||||
manualSorting: isManualSorting,
|
||||
pageCount: pagination?.totalItems ? Math.ceil(pagination.totalItems / pagination.limit) : -1,
|
||||
state: {
|
||||
rowSelection,
|
||||
|
||||
Reference in New Issue
Block a user