In Salesforce Lightning Web Components (LWC), deleting data doesn't require complex server-side logic. The Lightning Data Service (LDS) provides a built-in wire adapter function called deleteRecord that lets you remove records directly from your component with minimal effort.
deleteRecord is a standard LWC JavaScript function from lightning/uiRecordApi that lets you delete any Salesforce record using its Record ID without writing custom Apex code.
Step 1: Set Up the Component
Create a new Lightning Web Component in your Salesforce DX project or Developer Console and name it deleteRecordLWC.
Step 2: Add Component HTML Markup
Define a simple button that triggers the delete handler when clicked:
<template>
<lightning-button
label="Delete Record"
variant="destructive"
onclick={handleDelete}>
</lightning-button>
</template>
In this markup, the lightning-button invokes the handleDelete method in your JavaScript file upon click.
Step 3: Write the JavaScript Logic
Import deleteRecord from the lightning/uiRecordApi module and execute it inside your method:
import { LightningElement, api } from 'lwc';
import { deleteRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class DeleteRecordLWC extends LightningElement {
@api recordId; // Receives the record ID to delete
handleDelete() {
deleteRecord(this.recordId)
.then(() => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Record deleted successfully',
variant: 'success'
})
);
})
.catch(error => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error deleting record',
message: error.body.message,
variant: 'error'
})
);
});
}
}
Step 4: Pass the Record ID from a Parent Component
To use deleteRecordLWC inside another component or page, supply the target record ID through the public property:
<template>
<c-delete-record-lwc record-id="001XXXXXXXXXXXX"></c-delete-record-lwc>
</template>
- Module:
lightning/uiRecordApi - Parameters: Accepts a target record ID string.
- Return Type: Returns a JavaScript Promise (
Promise<void>). - Main Benefit: Removes server-side Apex dependencies and respects standard CRUD permissions automatically.
Conclusion
Using deleteRecord streamlines data management in Lightning Web Components. By leveraging built-in LDS utilities, you reduce code complexity, improve maintenance, and align with Salesforce best practices.