From 8846b520f4f59255fef82b8bf713673188b07d5f Mon Sep 17 00:00:00 2001 From: Lukas Willin Date: Tue, 28 May 2024 13:56:34 +0200 Subject: [PATCH] Fix losing row-state by updating rows individually (when rowId set) Instead of clearing the whole table, update each row individually to preserve row-state (like 'selection') --- src/DataTable.vue | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/DataTable.vue b/src/DataTable.vue index 8d21b94..1150955 100644 --- a/src/DataTable.vue +++ b/src/DataTable.vue @@ -74,8 +74,37 @@ watch( delete elements[keys[i]]; } - api.clear(); - api.rows.add(newVal).draw(false); + const rowId = api.context[0].rowId; + + // If no row id set clear table and add new data + if (!rowId) { + api.clear(); + api.rows.add(newVal).draw(false); + return; + } + + var key = api.context[0].rowId, + dataKeys = newVal.map(function (item: any) { return item[key]; }); + + // remove obsolete rows + api.rows(function (idx, rowData) { return !dataKeys.includes(rowData[key]); }).remove(); + + // update existing rows + var updatedKeys: any[] = []; + api.rows().every(function () { + var oldData = this.data(), + newData = newVal.find(function (x: any) { return x[key] === oldData[key]; }); + this.data(newData); + updatedKeys.push(newData[key]); + this.invalidate(); + }); + + // add missing rows + api.rows.add(newVal.filter(function (x: any) { + return updatedKeys.find(function (k) { return k === x[key]; }) === undefined; + })); + + api.draw(); }, { deep: true