primereact icon indicating copy to clipboard operation
primereact copied to clipboard

DataTable: Using dataKey with lazy VirtualScroller causes duplicate keys in rows

Open ssode opened this issue 1 year ago • 0 comments

Describe the bug

When using a DataTable with VirtualScroller enabled in lazy mode, providing a value for the dataKey prop will cause unwanted/undefined behavior due to duplicate keys in the rows.

This seems to be caused by the short circuit logic in ObjectUtils.resolveFieldData returning null in this function when the data for the row being rendered hasn't been loaded yet.

const getRowKey = (rowData, index) => {
    return props.dataKey ? ObjectUtils.resolveFieldData(rowData, props.dataKey) : index;
};
static resolveFieldData(data, field) {
        if (!data || !field) {
            // short circuit if there is nothing to resolve
            return null;
        }

React ends up coercing null to the string "null" and assigning it to multiple rows.

Reproducer

https://stackblitz.com/edit/jf8bvv?file=src%2FApp.jsx

PrimeReact version

9.6.4 - latest

React version

17.x

Language

TypeScript

Build / Runtime

Create React App (CRA)

Browser(s)

No response

Steps to reproduce the behavior

No response

Expected behavior

Not 100% sure, React docs state that the child's index will be used if no key is provided at all here, but that could cause issues since the index of the virtual row won't correlate to the data's array index . Maybe let dataKey accept a function that receives parameters such as the row index and allow the user to handle it (although undocumented, you can already pass a function to dataKey and it will receive the row data provided it's not null or undefined).

ssode avatar Mar 17 '24 02:03 ssode