Antd table is not updating on dataSource updates/changes

Viewed 5551
<Table
     columns={columnsStructure}
     dataSource={source}
     pagination={pagination}
     onChange={handleChange}
/>

the source is an array of objects. On component mount Table is rendering properly but once datSource i.e. source is updated, table rows remain the same.

How to resolve this issue. Wanted to update ant design table on source update.

4 Answers

To resolve this Ant-Design table data auto-update issue, you have to pass the data-source value as a clone of the observable value. like

<Table
     columns={columnsStructure}
     dataSource={[...source]}
     pagination={pagination}
     onChange={handleChange}
/>

The above solution did not work for me. I found that since the 'key' property of the row objects is remaining the same, React was not picking up the change.

What worked for me, though a bit hacky is generating a random key when a row object is changed. Hopefully the key is not being used for anything other than React to keep track of it, which is what it's usually meant for.

 const updatedEntry = {
    ...record,
    key: (Math.random() + 1).toString(36).substring(7),
    //anyproperty : //yourValue
      }
      

Still looking for more cleaner solutions to this problem.

This is a trap of shallow comparison.

If you reused the objects in the oldDataSource to increase efficiency, like:

const newDataSource=[...oldDataSource]
newDataSource[0].column1="newValue"
setDatasource(newDataSource)

This will not work. Yes, the table is updating, because you have a new list. However, the list components inside the table are not updating, because they see the old objects (although you changed the value). To make it work you need to do:

const newDataSource=[...oldDataSource]
newDataSource[0]={...newDataSource[0], column1: "newValue"}
setDatasource(newDataSource)

Then that row will update.

To resolve this Ant-Design table data auto-update issue, you have to pass the data-source value as a clone of the observable value. like

var _ = require('lodash');
...
<Table
     columns={columnsStructure}
     dataSource={_.cloneDeep(sources)}
     pagination={pagination}
     onChange={handleChange}
/>
Related