I am trying to delete a record based on the row selection in data table in LWC. So when a row is selected, the record Id is pushed to the array selectedIdsArray
but I am trying to pass it to the Apex method deleteAccount
but it doesn't work and always end up in catch block. Can anyone please explain where I am going wrong?
JavaScript:
import { LightningElement, wire, track,api } from "lwc";
import deleteListVi from "@salesforce/apex/DeleteListView.deleteListVi";
import { deleteRecord } from "lightning/uiRecordApi";
import { ShowToastEvent } from "lightning/platformShowToastEvent";
import deleteAccount from "@salesforce/apex/DeleteListView.deleteAccount";
export default class DeleteListView extends LightningElement {
@track columns = [
{
label: "Account Name",
fieldName: "Name"
},
{
label: "Website",
fieldName: "Website"
}
];
@track data;
@api selectedIdsArray = [];
@api recordId = [];
@wire(deleteListVi)
wireAccount({ error, data }) {
if (data) {
this.data = data;
} else if (data) {
this.error = error;
}
}
getrowId(event) {
const selectedRows = this.template.querySelector("lightning-datatable");
var selected = selectedRows.getSelectedRows();
for (const element of selected) {
//console.log("elementid", element.Id);
this.selectedIdsArray.push(element.Id);
}
console.log(this.selectedIdsArray);
}
handleClick(event) {
console.log("selectedEvent " + this.selectedIdsArray);
const recordId = this.selectedIdsArray;
console.log('recordId '+ recordId );
deleteAccount({accountIds: recordId})
.then(result => {
this.dispatchEvent(
new ShowToastEvent({
title: "Success",
message: "Account deleted",
variant: "success"
})
);
})
.catch(error => {
this.dispatchEvent(
new ShowToastEvent({
title: "Error deleting record",
message: "Error",
variant: "error"
})
);
});
}
}
Apex:
public with sharing class DeleteListView {
@AuraEnabled(cacheable = true)
public static List<Account> deleteListVi(){
return [SELECT Id, Name, Website FROM Account LIMIT 10];
}
@AuraEnabled
public static void deleteAccount(Id[] accountIds){
delete [SELECT Id,Name, Website FROM Account where Id IN: accountIds];
}
}
Edit 1:
Edit 2 – When I select two records, it duplicates the 1st record again and the end result is a total of 3 records. I am confused as to why this is happening.
Best Answer
That is because the selectedRows gives all the selected records in every selection.
Either you need to write a logic to check if array contains the id before push or use map method which creates new array and set all values everytime.
You can try updating your getrowId function to something like this.