Code: deleteAccount.js


/*eslint no-console: "error"*/
import { LightningElement, api } from 'lwc';
import { deleteRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';
 
export default class DeleteAccount extends NavigationMixin(LightningElement) {
    @api recordId; 
    deleteAccount(event) { 
        const recordId = event.target.dataset.recordid; 
        console.log('vh. - delete account' + recordId); 
        deleteRecord(recordId)
            .then(() => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Record Is  Deleted',
                        variant: 'success',
                    }),
                );
                this[NavigationMixin.Navigate]({
                    type: 'standard__objectPage',
                    attributes: {
                        objectApiName: 'Account',
                        actionName: 'home',
                    },
                });
            })
            .catch(error => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error While Deleting record',
                        message: error.message,
                        variant: 'error',
                    }),
                );
            });
    }
}

Yes there’s a lot more in here than we’ve seen in our previous JavaScript files. I’ll focus on what’s important for the Delete operation.

import { deleteRecord } from 'lightning/uiRecordApi';

This line of code imports the deleteRecord function from the LWC lightning/uiRecordApi. This is the JavaScript function that will actually perform the delete.

@api recordId;

The @api decorator exposes the recordID property as public, so it can be referenced in the HTML / template file.

NOTE: A field can have only 1 decorator.

const recordId = event.target.dataset.recordid;

During execution of DeleteAccount(), this line populates a new constant named recordID from the ID of the Account that hosts the Delete button of the lightning component. We should keep in mind that we’re building a lightning component that can be shown on account record pages

deleteRecord(recordId)

JavaScript function from the lightning/uiRecordApi that deletes the sObject record identified by recordID.

The other code in this file shows standard Lightning UI messages if the delete was successful or if it failed. If the action was successful the code sends the user to the default Account page.

Code: deleteAccount.js-meta.xml