Sub topic 14
Closing a Modal and Handling the Result
This chapter covers how a LightningModal ends and how the component that opened it receives a value back. It assumes you can build a basic LWC, use @api properties, and write async/await code. It also assumes you have already seen how a modal template is built and how open() is called.
How a modal returns a value
A modal does not return a value directly. The opener calls the static open() method, which returns a Promise. That Promise resolves when the modal calls this.close(result). Whatever you pass to close() becomes the resolved value.
The modal is removed from the page after close() runs. You cannot read its state later, so everything the opener needs must go through the result.
Calling close
close() is a method inherited from LightningModal. It takes one optional argument of any type.
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');
}
}The two handlers return different strings. The opener decides what to do by looking at the string. This is the simplest pattern and works well for yes/no decisions.
If you call close() with no argument, the Promise resolves with undefined.
Handling the result in the opener
Use await inside an async method, then branch on the result.
import { LightningElement } from 'lwc';
import ConfirmDeleteModal from 'c/confirmDeleteModal';
export default class ModalOpener extends LightningElement {
async handleDeleteClick() {
const result = await ConfirmDeleteModal.open({
size: 'small',
description: 'Confirm deletion of the selected record',
label: 'Confirm delete',
recordName: 'Acme Corp'
});
if (result === 'confirm') {
// continue with the delete
}
}
}You can also use .then() if you prefer, because open() returns an ordinary Promise.
Every exit path resolves the Promise
A user can leave a modal in more than one way:
- Clicking a button that calls
close(). - Clicking the X in the header.
- Pressing the Escape key.
The last two do not call your handlers. The Promise still resolves, and the result is undefined. This is the most common source of bugs. Code that checks only for 'cancel' will treat an Escape press as something else.
For that reason, test for the positive case and treat everything else as a cancel:
const result = await ConfirmDeleteModal.open({
size: 'small',
description: 'Confirm deletion of the selected record',
label: 'Confirm delete',
recordName: 'Acme Corp'
});
if (result !== 'confirm') {
return;
}This is safer than if (result === 'cancel'), because only an explicit confirmation lets the action proceed.
Returning structured results
The result can be an object. Use this when the modal collects input.
import { api } from 'lwc';
import LightningModal from 'lightning/modal';
export default class RenameModal extends LightningModal {
@api currentName;
newName;
handleInput(event) {
this.newName = event.target.value;
}
handleCancel() {
this.close({ status: 'cancel' });
}
handleSave() {
this.close({ status: 'save', name: this.newName });
}
}The opener then reads the fields:
import { LightningElement } from 'lwc';
import RenameModal from 'c/renameModal';
export default class RenameOpener extends LightningElement {
name = 'Acme Corp';
async handleRename() {
const result = await RenameModal.open({
size: 'small',
label: 'Rename account',
description: 'Enter a new name for the account',
currentName: this.name
});
if (result && result.status === 'save') {
this.name = result.name;
}
}
}The result && guard matters. Without it, an Escape press gives undefined, and reading .status on it throws a TypeError.
A short table of the patterns:
| Pattern | Result value | Best for |
|---|---|---|
| String flag | `'confirm'` or `'cancel'` | Yes/no decisions |
| Object | `{ status, ...data }` | Forms that return input |
| No argument | `undefined` | Informational modals |
Disabling close for required choices
Some modals must not be dismissed with Escape or X. Set disableClose to true inside the modal to block those paths while work is in progress, for example during a save. Set it back to false when the work finishes.
import { api } from 'lwc';
import LightningModal from 'lightning/modal';
export default class SavingModal extends LightningModal {
@api recordName;
async handleSave() {
this.disableClose = true;
try {
await this.doSave();
this.close('saved');
} finally {
this.disableClose = false;
}
}
doSave() {
return new Promise((resolve) => setTimeout(resolve, 1000));
}
}While disableClose is true, the X button and Escape do nothing. Calling this.close() yourself still works.
Handling errors
The Promise from open() resolves; it does not reject for user cancellation. A rejection is possible only when something goes wrong opening the modal, for example if you pass invalid options. Wrap the call in try/catch when the surrounding flow must stay safe.
async handleOpen() {
try {
const result = await ConfirmDeleteModal.open({
size: 'small',
label: 'Confirm delete',
description: 'Confirm deletion',
recordName: 'Acme Corp'
});
if (result === 'confirm') {
// proceed
}
} catch (error) {
console.error('Modal failed', error);
}
}Do work that might fail, such as a save, in the opener after the modal closes, or in the modal before it calls close(). Choose one place. If the modal saves and then closes with 'saved', the opener should only show the toast or navigate.
Common mistakes
- Reading the result as if
close()always receives a value. It can beundefined. - Forgetting
asyncon the handler that usesawait, which is a syntax error. - Trying to keep a reference to the modal instance and call methods on it. The modal is gone after it closes.
- Treating a closed modal like a rejected Promise. Cancel is a normal resolution.
- Passing non-serializable assumptions: return plain data, not component references.
Exercises
Exercise
A user opens your confirm modal and presses Escape. What does await ConfirmDeleteModal.open(...) return, and why does if (result !== 'cancel') { deleteIt(); } cause a bug?
Show answer
It returns undefined, because dismissing with Escape or the X resolves the Promise without calling your handlers. Since undefined !== 'cancel' is true, the delete would run. Check for the positive value instead: if (result === 'confirm').
Exercise
A modal closes with this.close({ status: 'save', name: this.newName }). Write the condition the opener should use before reading result.name.
Show answer
if (result && result.status === 'save'). The result && part guards against undefined when the user dismissed the modal without saving.