[SalesForce] Lightning datatable checkbox remains checked after multi delete in LWC

In my LWC, I have multi-delete functionality. I need to check the records using checkbox and press the delete button to delete. After deleting a record, the next record automatically gets checked. Ideally, all checkboxes should remain unchecked after delete is completed.

EG: Please find the screenshot below. Out of 3 records, I deleted 1st record and after it was deleted, the checkbox remained checked for the 2nd record.

How can I clear the checkbox after deletion? I checked here. It's working fine for aura but not for LWC. Is it a salesforce issue? Please guide. Thank you!
enter image description here

Datatable code.

<div class="slds-table_bordered slds-table_striped slds-scrollable slds-m-around_medium">
            <lightning-datatable key-field="id" data={addresses} columns={columns} onrowaction={handleRowActions}>
            </lightning-datatable>
</div>

Delete button code.

deleteAdd(currentRow) {
        let selected = this.template.querySelector('lightning-datatable').getSelectedRows();//get selected records
        let CRIdArray = [];//add all relationship IDs in array 
        selected.forEach(row => {
            if (row.Role!=='Account') {
                CRIdArray.push(row.CRId);
            }
        });
            deleteAddress({deleteIds: CRIdArray})//delete address using apex
            .then(result => {
                // refreshing table data using refresh apex
                return refreshApex(this.refreshTable);
            })
            .catch(error => { //Showing error if any
                //catch errors
            });
}

Best Answer

As it stands now, I'm pretty sure you're "recycling" the id field, which is causing the odd behavior you're seeing. Each row in the table should have a unique ID (such as the Salesforce ID), and should not be generated in a way that an unrelated row should match an ID of a previously selected row. The key field is used to determine if a row is a different row than a previous render, so if you're recycling ID values, this is the behavior you get.

You should apparently be using CRId as your key field:

<lightning-datatable key-field="CRId" data={addresses} columns={columns} onrowaction={handleRowActions}>

Side note:

In JavaScript, it's customary to use the appropriate Array method instead of this awkward forEach-push loop. In your case:

let CRIdArray = selected.map(row => row.CRId);
Related Topic