Lightning Datatable – Delete in LWC Lightning Datatable Is Not Working

lightning-datatablelightning-web-components

I have a requirement to add Delete column for lwc lightning datatable, where I am able to display the Delete button. While clicking on the Delete button was not getting the recordid for the row which user has clicked on. Below is the code which I have used

<lightning-datatable key-field="Id" data={datalist} columns={Columns} hide-checkbox-column  onrowaction={callRowAction}>
            </lightning-datatable>

JS

const Columns = [
    { label: 'User Name', fieldName: 'userNameURL', type: 'url', typeAttributes: { label: { fieldName: 'createdby' }, target: '_self' } },
    { label: 'Type', fieldName: 'type' },
    { label: 'Delete',  type: "button", typeAttributes: { label: 'Delete', name: 'Delete', title: 'Delete',  disabled: false,   iconPosition: 'left',  iconName:'utility:delete' }  }
];


@wire(getRecords, {recId: '$recordId'})
    wiredRecords(result) {  
        if (result.data) {
            
            let recArray = [];            
            result.data.forEach(rec => {
                this.RecordCount +=1;
                let recRow = {};   
                recRow.id = rec.Id;  
                recRow.createdby = rec.CreatedBy.Name;
                recRow.createdByURL = '/lightning/r/User/' + rec.CreatedById + '/view';
                recRow.type = rec.Account_Type__c;                                
                
                recArray.push(recRow);
            });
            this.datalist = recArray;  
        } else if (result.error) {
            this.error = result.error;   
        }
    }
    



callRowAction(event) {
        const recId = event.detail.row.Id;
        
        console.log('event.currentTarget.dataset.id ', event.currentTarget.dataset.id);  //Output is undefined
        console.log('event.currentTarget.dataset.Id ', event.currentTarget.dataset.Id);  //Output is undefined
        console.log('callrowaction ', recId);                       //Output is undefined
    this.handleDeleteRow(recId);          
    }

I have shortened the code in the wire method as we need some business logic so instead of populating directly using "data" was looping through the records and processing them.

When user clicks on the Delete button for any particular row in the callRowAction method, for the console.log getting "Output as undefined", not sure how to capture the record id for this sceanrio. Once I can get record Id then I can make a progress. Thanks in advance.

Best Answer

const recId = event.detail.row.Id;

Should be:

const recId = event.detail.row.id;

Note that JavaScript is case sensitive, so you must make sure you check the correct casing of variables.

Note that event.currentTarget or even event.target won't return a dataset property, because this is a lightning-datatable, so you'd only get a property on the lightning-datatable itself.