Sub topic 17
Putting it together: confirm, save, toast, and navigate
This chapter combines the three building blocks into one user flow: a user clicks Delete on an account, confirms in a modal, the record is deleted, a toast reports the result, and the app moves to the Account home page.
It assumes you already know the basics of Lightning Web Components (template, JavaScript class, metadata file), @api and dispatchEvent, Promises with async/await, and Salesforce records and record IDs. It also assumes you have read the earlier chapters on ShowToastEvent, NavigationMixin, and LightningModal.
The flow at a glance
The flow has four steps, and each step depends on the result of the previous one.
- Open a confirmation modal and wait for the user's answer.
- If the user confirmed, delete the record.
- Show a toast that reports success or failure.
- On success, navigate away from the page that no longer has a record to show.
Step 1: The modal component
The modal is a separate component that extends LightningModal. Its template uses the header, body, and footer components as top-level content.
<template>
<lightning-modal-header label={label}></lightning-modal-header>
<lightning-modal-body>
<p>Delete {recordName}? This cannot be undone.</p>
</lightning-modal-body>
<lightning-modal-footer>
<lightning-button label="Cancel" onclick={handleCancel}></lightning-button>
<lightning-button variant="destructive" label="Delete" onclick={handleConfirm}></lightning-button>
</lightning-modal-footer>
</template>The class receives recordName through an @api property. The label property is inherited from LightningModal, so the label option you pass to open fills the header. Each button calls this.close with a string, and that string becomes the result the opener receives.
import { api } from 'lwc';
import LightningModal from 'lightning/modal';
export default class ConfirmDeleteModal extends LightningModal {
@api recordName;
handleCancel() {
this.close('cancel');
}
handleConfirm() {
this.close('confirm');
}
}Closing the modal with the X button or the Escape key also resolves the Promise, with undefined as the result. The parent must therefore not assume that the result is always one of your two strings.
Step 2: Opening the modal and waiting for the answer
ConfirmDeleteModal.open is a static method. It takes the built-in options (size, description, label) and any values for your @api properties, and it returns a Promise. Awaiting that Promise pauses the handler until the modal closes.
const result = await ConfirmDeleteModal.open({
size: 'small',
description: 'Confirm deletion of this account',
label: 'Confirm delete',
recordName: 'this account'
});
if (result !== 'confirm') {
return;
}Checking result !== 'confirm' instead of result === 'cancel' is deliberate. Any answer other than an explicit confirmation, including a dismissed dialog, stops the flow. For a destructive action, the safe default is to do nothing.
The description option is not shown on screen. It gives screen readers a description of the modal, so write it as a sentence that explains the purpose of the dialog.
Step 3: Deleting the record and reporting the result
deleteRecord from lightning/uiRecordApi takes a record ID and returns a Promise. If it fails, the Promise rejects, so you wrap it in try/catch.
On success, dispatch a ShowToastEvent with the success variant. On failure, dispatch one with the error variant and sticky mode so the user has time to read the message.
try {
await deleteRecord(this.recordId);
this.dispatchEvent(
new ShowToastEvent({
title: 'Deleted',
message: 'The account was deleted.',
variant: 'success'
})
);
// navigate here
} catch (error) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Delete failed',
message: error.body ? error.body.message : error.message,
variant: 'error',
mode: 'sticky'
})
);
}Errors from Salesforce usually carry the useful text in error.body.message. Errors thrown by JavaScript itself have only error.message. The ternary handles both.
Step 4: Navigating away
After a successful delete, the record page the user is looking at no longer has a record behind it. Send the user to the Account home page with a standard__objectPage page reference and the home action.
this[NavigationMixin.Navigate]({
type: 'standard__objectPage',
attributes: {
objectApiName: 'Account',
actionName: 'home'
}
});For this[NavigationMixin.Navigate] to exist, the class must extend NavigationMixin(LightningElement) instead of LightningElement directly.
The complete component
import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { deleteRecord } from 'lightning/uiRecordApi';
import ConfirmDeleteModal from 'c/confirmDeleteModal';
export default class DeleteAccount extends NavigationMixin(LightningElement) {
@api recordId;
async handleDelete() {
const result = await ConfirmDeleteModal.open({
size: 'small',
description: 'Confirm deletion of this account',
label: 'Confirm delete',
recordName: 'this account'
});
if (result !== 'confirm') {
return;
}
try {
await deleteRecord(this.recordId);
this.dispatchEvent(
new ShowToastEvent({
title: 'Deleted',
message: 'The account was deleted.',
variant: 'success'
})
);
this[NavigationMixin.Navigate]({
type: 'standard__objectPage',
attributes: {
objectApiName: 'Account',
actionName: 'home'
}
});
} catch (error) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Delete failed',
message: error.body ? error.body.message : error.message,
variant: 'error',
mode: 'sticky'
})
);
}
}
}A minimal template for the parent only needs a button that calls the handler:
<template>
<lightning-button
variant="destructive-text"
label="Delete account"
onclick={handleDelete}
></lightning-button>
</template>Design decisions and edge cases
Why the toast comes before the navigation
The toast is dispatched first, then the navigation starts. Toasts in Lightning Experience live in the page shell, not inside the component, so they stay visible after the user moves to another page. The order also means that if navigation throws, the user has already been told the delete worked.
Why the navigation sits inside the `try` block
The catch block is meant to handle delete failures. Because Navigate is inside the same try, an unexpected error from it would show a "Delete failed" toast, which would be misleading since the record is already gone. If you want to keep the two apart, set a flag after deleteRecord succeeds, or move the toast and navigation after the try/catch using a variable that records success.
let deleted = false;
try {
await deleteRecord(this.recordId);
deleted = true;
} catch (error) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Delete failed',
message: error.body ? error.body.message : error.message,
variant: 'error',
mode: 'sticky'
})
);
}
if (deleted) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Deleted',
message: 'The account was deleted.',
variant: 'success'
})
);
this[NavigationMixin.Navigate]({
type: 'standard__objectPage',
attributes: { objectApiName: 'Account', actionName: 'home' }
});
}Choosing toast modes in this flow
| Outcome | Variant | Mode | Reason |
|---|---|---|---|
| Delete succeeded | `success` | default (`dismissible`) | The message is short and the user is leaving the page anyway. |
| Delete failed | `error` | `sticky` | The user needs time to read the reason and decide what to do. |
Common errors
this[NavigationMixin.Navigate] is not a function. The class extendsLightningElementinstead ofNavigationMixin(LightningElement).- The modal never opens or
openis undefined. The import path is wrong, or the modal class does not extendLightningModal. Import the modal by its component name, such asc/confirmDeleteModal. - Values passed to
opendo not appear in the modal. Each value must match a property marked@apiin the modal class. Properties without@apiare ignored. - The flow keeps going after the user closes the dialog. The code tests for
'cancel'only. Test for'confirm'and return on anything else. - The toast message shows
[object Object]. Theerroris a Salesforce error object, and the code passed it directly asmessage. Readerror.body.messageinstead.
Exercises
Exercise
In DeleteAccount, the user closes the modal by pressing the Escape key. What value does result hold, and what does the component do next?
Show answer
result is undefined, because the modal closed without calling this.close with a value. The check result !== 'confirm' is true, so the handler returns. The record is not deleted, no toast appears, and no navigation happens.
Exercise
Change the flow so that a successful delete shows a toast with a sticky mode and a link labelled "Go to accounts" that points to /lightning/o/Account/home, and the component no longer navigates automatically. What do you change in the toast?
Show answer
Remove the Navigate call and add messageData with a placeholder in message. For example: message: 'The account was deleted. {0}', messageData: [{ url: '/lightning/o/Account/home', label: 'Go to accounts' }], and mode: 'sticky', keeping variant: 'success'.
Exercise
A teammate wants to move Navigate out of the try block so a navigation error cannot show "Delete failed". Describe one way to do it without changing the behavior for a normal successful delete.
Show answer
Declare let deleted = false; before the try, set deleted = true; right after await deleteRecord(this.recordId);, and keep only the error toast in catch. After the try/catch, run if (deleted) { ... } to dispatch the success toast and call this[NavigationMixin.Navigate].