Salesforce Interview Questions & Answers Book is now available!

Grab Now

LWC

How to use deleteRecord in LWC

Let's look at how to delete a record using deleteRecord named import in LWC.

By Teja, ex-Salesforce engineer · Updated February 18, 2021 · 1 min read

Let's look at how to delete a record using deleteRecord named import in LWC.

It's definitely very simple than using the other methods (createRecord & updateRecord).

Here is a sample snippet.

import { api, LightningElement } from "lwc";

//1. Import a named import ShowToastEvent
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

//2. Import deleteRecord named import
import { deleteRecord } from "lightning/uiRecordApi";

export default class ExploreDeleteRecord extends LightningElement {
  
  //3. We would need a recordId 
  @api
  recordId;

    
  handleClick() {
  
      //4. Invoke the deleteRecord to delete a record
    deleteRecord(this.recordId)
      .then(() => {
      
          //5. We are firing a toast message
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Success',
                message: 'Record deleted',
                variant: 'success'
            })
        );
      })
      .catch((error) => {
        console.log(error);
      });
  }
}

exploreDeleteRecord.js

Here is the template file.

<template>
  <lightning-button label="Delete" onclick={handleClick}></lightning-button>
</template>

exploreDeleteRecord.html

Hope this is helpful!

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion — one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts