Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion packages/table-core/src/core/table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,29 @@ export function createTable<TData extends RowData>(

const queued: (() => void)[] = []
let queuedTimeout = false
let getColumnCache = new WeakMap<
ColumnDef<TData, unknown>[],
Record<string, Column<TData, unknown>>
>()

const getColumnFromCache = (columnId: string) => {
const columnDefs = table.options.columns
let columnsById = getColumnCache.get(columnDefs)

if (!columnsById) {
columnsById = table.getAllFlatColumns().reduce(
(acc, column) => {
acc[column.id] = column
return acc
},
{} as Record<string, Column<TData, unknown>>
)
Comment on lines +336 to +342

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this not using table._getAllFlatColumnsById()[columnId]?


getColumnCache.set(columnDefs, columnsById)
}

return columnsById[columnId]
}

const coreInstance: CoreInstance<TData> = {
_features,
Expand Down Expand Up @@ -506,7 +529,7 @@ export function createTable<TData extends RowData>(
),

getColumn: columnId => {
const column = table._getAllFlatColumnsById()[columnId]
const column = getColumnFromCache(columnId)

if (process.env.NODE_ENV !== 'production' && !column) {
console.error(`[Table] Column with id '${columnId}' does not exist.`)
Expand Down
48 changes: 48 additions & 0 deletions packages/table-core/tests/coreTable.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { describe, expect, it } from 'vitest'
import { ColumnDef, createTable, getCoreRowModel } from '../src'

type Person = {
firstName: string
lastName: string
}

describe('CoreTable', () => {
it('refreshes the column lookup cache when columns change without data changing', () => {
const data: Person[] = [{ firstName: 'Ada', lastName: 'Lovelace' }]
const firstNameColumns: ColumnDef<Person>[] = [
{
id: 'name',
accessorFn: row => row.firstName,
},
]
const lastNameColumns: ColumnDef<Person>[] = [
{
id: 'name',
accessorFn: row => row.lastName,
},
]

const table = createTable<Person>({
onStateChange() {},
renderFallbackValue: '',
data,
state: {},
columns: firstNameColumns,
getCoreRowModel: getCoreRowModel(),
})

const firstColumn = table.getColumn('name')
const row = table.getCoreRowModel().rows[0]!

expect(row.getValue('name')).toBe('Ada')

table.setOptions(old => ({
...old,
columns: lastNameColumns,
}))

expect(table.getCoreRowModel().rows[0]).toBe(row)
expect(table.getColumn('name')).not.toBe(firstColumn)
expect(row.getValue('name')).toBe('Lovelace')
})
})