|
| 1 | +import React, { useState } from "react" |
| 2 | + |
| 3 | +type SortDir = "asc" | "desc" |
| 4 | + |
| 5 | +type Column<T> = { |
| 6 | + key: keyof T |
| 7 | + label: string |
| 8 | + sortable?: boolean |
| 9 | +} |
| 10 | + |
| 11 | +type Props<T extends Record<string, unknown>> = { |
| 12 | + data: T[] |
| 13 | + columns: Column<T>[] |
| 14 | +} |
| 15 | + |
| 16 | +/** |
| 17 | + * DataTable with client-side sorting. |
| 18 | + * |
| 19 | + * BUG: The sort handler has a stale closure — it captures `sortDir` at the |
| 20 | + * time the handler is created, so toggling sort direction does not work |
| 21 | + * correctly after the first click. The second click always sorts in the same |
| 22 | + * direction as the first. |
| 23 | + * |
| 24 | + * Fix: use the functional form of setState — `setSortDir(prev => ...)` — |
| 25 | + * so the toggle always reads the current value. |
| 26 | + */ |
| 27 | +export function DataTable<T extends Record<string, unknown>>({ data, columns }: Props<T>) { |
| 28 | + const [sortKey, setSortKey] = useState<keyof T | null>(null) |
| 29 | + const [sortDir, setSortDir] = useState<SortDir>("asc") |
| 30 | + |
| 31 | + // BUG: stale closure — sortDir is captured at handler creation time |
| 32 | + const handleSort = (key: keyof T) => { |
| 33 | + if (sortKey === key) { |
| 34 | + setSortDir(sortDir === "asc" ? "desc" : "asc") // BUG: reads stale sortDir |
| 35 | + } else { |
| 36 | + setSortKey(key) |
| 37 | + setSortDir("asc") |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + const sorted = sortKey |
| 42 | + ? [...data].sort((a, b) => { |
| 43 | + const av = a[sortKey] |
| 44 | + const bv = b[sortKey] |
| 45 | + const cmp = av < bv ? -1 : av > bv ? 1 : 0 |
| 46 | + return sortDir === "asc" ? cmp : -cmp |
| 47 | + }) |
| 48 | + : data |
| 49 | + |
| 50 | + return ( |
| 51 | + <table> |
| 52 | + <thead> |
| 53 | + <tr> |
| 54 | + {columns.map((col) => ( |
| 55 | + <th |
| 56 | + key={String(col.key)} |
| 57 | + onClick={col.sortable ? () => handleSort(col.key) : undefined} |
| 58 | + aria-sort={sortKey === col.key ? (sortDir === "asc" ? "ascending" : "descending") : undefined} |
| 59 | + > |
| 60 | + {col.label} |
| 61 | + </th> |
| 62 | + ))} |
| 63 | + </tr> |
| 64 | + </thead> |
| 65 | + <tbody> |
| 66 | + {sorted.map((row, i) => ( |
| 67 | + <tr key={i}> |
| 68 | + {columns.map((col) => ( |
| 69 | + <td key={String(col.key)}>{String(row[col.key])}</td> |
| 70 | + ))} |
| 71 | + </tr> |
| 72 | + ))} |
| 73 | + </tbody> |
| 74 | + </table> |
| 75 | + ) |
| 76 | +} |
0 commit comments