MCPcopy Index your code
hub / github.com/primer/react / useTable

Function useTable

packages/react/src/DataTable/useTable.ts:45–211  ·  view source on GitHub ↗
({
  columns,
  data,
  initialSortColumn,
  initialSortDirection,
}: TableConfig<Data>)

Source from the content-addressed store, hash-verified

43type ColumnSortState = {id: string | number; direction: Exclude<SortDirection, 'NONE'>} | null
44
45export function useTable<Data extends UniqueRow>({
46 columns,
47 data,
48 initialSortColumn,
49 initialSortDirection,
50}: TableConfig<Data>): Table<Data> {
51 const [rowOrder, setRowOrder] = useState(data)
52 const [prevData, setPrevData] = useState(data)
53 const [prevColumns, setPrevColumns] = useState(columns)
54 const [sortByColumn, setSortByColumn] = useState<ColumnSortState>(() => {
55 return getInitialSortState(columns, initialSortColumn, initialSortDirection)
56 })
57 const {gridTemplateColumns} = useTableLayout(columns)
58
59 // Reset the `sortByColumn` state if the columns change and that column is no
60 // longer provided
61 if (columns !== prevColumns) {
62 setPrevColumns(columns)
63 if (sortByColumn) {
64 const column = columns.find(column => {
65 const id = column.id ?? column.field
66 return sortByColumn.id === id
67 })
68 if (!column) {
69 setSortByColumn(null)
70 }
71 }
72 }
73
74 const headers = columns.map(column => {
75 const id = column.id ?? column.field
76 if (id === undefined) {
77 throw new Error(`Expected either an \`id\` or \`field\` to be defined for a Column`)
78 }
79
80 const sortable = column.sortBy !== undefined && column.sortBy !== false
81 return {
82 id,
83 column,
84 isSortable() {
85 return sortable
86 },
87 getSortDirection() {
88 if (sortByColumn && sortByColumn.id === id) {
89 return sortByColumn.direction
90 }
91 return SortDirection.NONE
92 },
93 }
94 })
95
96 // Update the row order and apply the current sort column to the incoming data
97 if (data !== prevData) {
98 setPrevData(data)
99 setRowOrder(data)
100 if (sortByColumn) {
101 sortRows(sortByColumn)
102 }

Callers 1

DataTableFunction · 0.90

Calls 3

getInitialSortStateFunction · 0.85
useTableLayoutFunction · 0.85
sortRowsFunction · 0.85

Tested by

no test coverage detected