|
| 1 | +--- |
| 2 | +title: Remote Column Sorting |
| 3 | +description: Use shadcn header buttons to send sort params to a remote data model. |
| 4 | +sidebar: |
| 5 | + label: Remote Sorting |
| 6 | +--- |
| 7 | + |
| 8 | +Each sortable column header sends a `sort` action to the remote model. The action updates the request params, the model refetches from the first page, and the active header button reads the current sort from `modelActionState$`. |
| 9 | + |
| 10 | +The shadcn `SortHeaderButton` defaults to a payload shaped as `{ field, direction }`, where `direction` cycles through `'asc'`, `'desc'`, and no sort. |
| 11 | + |
| 12 | +## APIs used |
| 13 | + |
| 14 | +- `remoteModel()` — refetches rows when request params change |
| 15 | +- `SortHeaderButton` — shadcn slot component for column-header sorting |
| 16 | +- `HeaderEnd` — places the sort button after the header label |
| 17 | +- `computeRowKey` — keeps row identity stable when sorting reorders rows |
| 18 | + |
| 19 | +```tsx live wide file=App.tsx |
| 20 | +import { useState } from 'react' |
| 21 | + |
| 22 | +import { DataTable, DataTableCell, DataTableColumn, DataTableColumnHeader, HeaderEnd } from '@/components/ui/data-table' |
| 23 | +import { SortHeaderButton } from '@/components/ui/data-table/column-sort' |
| 24 | +import { defaultOffsetViewportHandler, remoteModel } from '@virtuoso.dev/data-table' |
| 25 | + |
| 26 | +import { fetchProducts, placeholder } from './api' |
| 27 | + |
| 28 | +import type { Product, Query } from './api' |
| 29 | + |
| 30 | +export default function App() { |
| 31 | + const [model] = useState(() => |
| 32 | + remoteModel<Product, Query>({ |
| 33 | + actions: { |
| 34 | + sort: { |
| 35 | + strategy: 'supersede', |
| 36 | + handler: ({ params, payload }) => ({ ...params, sort: payload as Query['sort'] }), |
| 37 | + }, |
| 38 | + }, |
| 39 | + fetch: fetchProducts, |
| 40 | + initialParams: {}, |
| 41 | + onViewportChange: defaultOffsetViewportHandler, |
| 42 | + pageSize: 40, |
| 43 | + placeholder, |
| 44 | + }) |
| 45 | + ) |
| 46 | + |
| 47 | + return ( |
| 48 | + <DataTable className="rounded-xl" computeRowKey={({ data }) => data.id} model={model} style={{ height: 420 }}> |
| 49 | + <DataTableColumn field="name"> |
| 50 | + <DataTableColumnHeader> |
| 51 | + <HeaderEnd component={SortHeaderButton} /> |
| 52 | + {() => 'Product'} |
| 53 | + </DataTableColumnHeader> |
| 54 | + <DataTableCell className="font-medium">{({ row }) => row.data.name}</DataTableCell> |
| 55 | + </DataTableColumn> |
| 56 | + <DataTableColumn field="category"> |
| 57 | + <DataTableColumnHeader> |
| 58 | + <HeaderEnd component={SortHeaderButton} /> |
| 59 | + {() => 'Category'} |
| 60 | + </DataTableColumnHeader> |
| 61 | + <DataTableCell>{({ cellValue }) => String(cellValue)}</DataTableCell> |
| 62 | + </DataTableColumn> |
| 63 | + <DataTableColumn field="price"> |
| 64 | + <DataTableColumnHeader className="justify-end"> |
| 65 | + <HeaderEnd component={SortHeaderButton} /> |
| 66 | + {() => 'Price'} |
| 67 | + </DataTableColumnHeader> |
| 68 | + <DataTableCell className="text-right tabular-nums">{({ cellValue }) => `$${cellValue}`}</DataTableCell> |
| 69 | + </DataTableColumn> |
| 70 | + </DataTable> |
| 71 | + ) |
| 72 | +} |
| 73 | +``` |
| 74 | + |
| 75 | +```ts live file=api.ts |
| 76 | +import type { FetchParams } from '@virtuoso.dev/data-table' |
| 77 | + |
| 78 | +export interface Product { |
| 79 | + id: string |
| 80 | + name: string |
| 81 | + category: 'Office' | 'Peripherals' | 'Audio' |
| 82 | + price: number |
| 83 | +} |
| 84 | + |
| 85 | +export interface Query { |
| 86 | + sort?: { |
| 87 | + field: 'name' | 'category' | 'price' |
| 88 | + direction: 'asc' | 'desc' |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +const categories: Product['category'][] = ['Office', 'Peripherals', 'Audio'] |
| 93 | + |
| 94 | +const allProducts: Product[] = Array.from({ length: 240 }, (_, index) => ({ |
| 95 | + id: `SKU-${String(index + 1).padStart(3, '0')}`, |
| 96 | + name: `${categories[index % categories.length]} Item ${index + 1}`, |
| 97 | + category: categories[index % categories.length]!, |
| 98 | + price: 49 + (index % 11) * 13, |
| 99 | +})) |
| 100 | + |
| 101 | +export const placeholder: Product = { |
| 102 | + id: 'loading', |
| 103 | + name: 'Loading...', |
| 104 | + category: 'Office', |
| 105 | + price: 0, |
| 106 | +} |
| 107 | + |
| 108 | +async function pause(ms: number, signal: AbortSignal) { |
| 109 | + await new Promise<void>((resolve, reject) => { |
| 110 | + const timer = window.setTimeout(resolve, ms) |
| 111 | + signal.addEventListener( |
| 112 | + 'abort', |
| 113 | + () => { |
| 114 | + window.clearTimeout(timer) |
| 115 | + reject(new Error('aborted')) |
| 116 | + }, |
| 117 | + { once: true } |
| 118 | + ) |
| 119 | + }) |
| 120 | +} |
| 121 | + |
| 122 | +function compareProducts(sort: NonNullable<Query['sort']>) { |
| 123 | + return (left: Product, right: Product) => { |
| 124 | + const leftValue = left[sort.field] |
| 125 | + const rightValue = right[sort.field] |
| 126 | + const result = |
| 127 | + typeof leftValue === 'number' && typeof rightValue === 'number' |
| 128 | + ? leftValue - rightValue |
| 129 | + : String(leftValue).localeCompare(String(rightValue), undefined, { numeric: true }) |
| 130 | + |
| 131 | + return sort.direction === 'asc' ? result : -result |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +export async function fetchProducts(params: FetchParams<Query>) { |
| 136 | + await pause(180, params.signal) |
| 137 | + const data = params.params.sort ? allProducts.toSorted(compareProducts(params.params.sort)) : allProducts |
| 138 | + |
| 139 | + return { |
| 140 | + rows: data.slice(params.offset, params.offset + params.limit), |
| 141 | + totalCount: data.length, |
| 142 | + } |
| 143 | +} |
| 144 | +``` |
| 145 | + |
| 146 | +## When this doesn't fit |
| 147 | + |
| 148 | +If your API uses a different query shape, render the button manually in `HeaderEnd` and pass `action`, `field`, `getDirection`, or `getPayload` props to `SortHeaderButton`. Copy the installed component into your app-specific table wrapper when every table in the app should share the same sort payload shape. |
0 commit comments