Sub topic 8
Closing the action panel
A screen quick action opens a modal panel. The panel stays open until something closes it. Your component can't remove the panel by itself, so it asks the platform to do it by dispatching a CloseActionScreenEvent. This chapter covers when to dispatch that event, where to place it relative to the save and the toast, and how to test it.
This chapter assumes you can build a screen action with lightning-quick-action-panel and call updateRecord, and that you know how dispatchEvent works in LWC. The examples reuse the UpdateDescription component from earlier chapters.
What CloseActionScreenEvent does
CloseActionScreenEvent comes from the lightning/actions module. It is a standard DOM event that the quick action host listens for. When the host receives it, it dismisses the modal and destroys your component.
import { CloseActionScreenEvent } from 'lightning/actions';
// Inside any method of the component
this.dispatchEvent(new CloseActionScreenEvent());Three details matter in practice:
- You construct it with no arguments. It carries no payload, so you can't pass a result back to the page.
- You dispatch it from the component's own host with
this.dispatchEvent. You don't needbubblesorcomposed, because the platform wrapper that hosts your component receives it. - It only does something in a screen action. A headless action has no panel, so there is nothing to close.
Where to dispatch it
A screen action usually has two exits: the user cancels, or the work succeeds. Each exit calls the same event.
Cancel
The Cancel button should close the panel without touching any data.
handleCancel() {
this.dispatchEvent(new CloseActionScreenEvent());
}Success
After a successful save, show feedback and then close. The full handler from the earlier chapter does this:
async handleSave() {
this.isSaving = true;
const fields = {};
fields[ID_FIELD.fieldApiName] = this.recordId;
fields[DESCRIPTION_FIELD.fieldApiName] = this.description;
try {
await updateRecord({ fields });
this.dispatchEvent(new ShowToastEvent({
title: 'Success',
message: 'Description updated',
variant: 'success'
}));
this.dispatchEvent(new CloseActionScreenEvent());
} catch (error) {
this.dispatchEvent(new ShowToastEvent({
title: 'Error updating record',
message: error?.body?.message || 'Unknown error',
variant: 'error'
}));
} finally {
this.isSaving = false;
}
}The CloseActionScreenEvent is inside the try block, after the await. It runs only if updateRecord resolved. The catch block shows an error toast and leaves the panel open.
The order of save, toast and close
The sequence is: wait for the save, show the toast, close the panel.
Closing the panel does not cancel the toast. The toast belongs to the page, not to your component, so it stays visible after your component is destroyed. That is why you can safely dispatch both events one after the other.
The order of the two dispatches is not critical, but the order relative to the await is. If you close before the save finishes, the component is destroyed while the request is still in flight. The save may still complete on the server, but your then or catch code may run against a component that no longer exists, and the user sees no confirmation or error.
// Wrong: closes before the save result is known
updateRecord({ fields });
this.dispatchEvent(new CloseActionScreenEvent());
// Right: close only after the promise resolves
await updateRecord({ fields });
this.dispatchEvent(new CloseActionScreenEvent());Keeping the panel open on failure
When a save fails, the user needs a chance to fix the input or retry. Closing the panel on an error throws away what they typed. Show an error toast and leave the panel open, as the catch block above does.
Note the finally block. It resets isSaving so the Save button becomes enabled again after a failure. On success the component is about to be destroyed, so the reset does nothing visible. It is still correct, because it keeps the state consistent on both paths.
You can also validate before saving, so that fewer failures reach the server. A simple guard looks like this:
async handleSave() {
if (!this.description || this.description.length > 32000) {
this.dispatchEvent(new ShowToastEvent({
title: 'Invalid description',
message: 'Enter a description of up to 32,000 characters',
variant: 'warning'
}));
return;
}
// ...save logic as above
}Returning early means no close event is dispatched, and the panel stays open.
Ways the panel closes without your code
You don't control every exit. The user can click the X in the panel header, press Escape, or navigate elsewhere. In these cases the platform removes your component without any event from you.
Two consequences follow:
- Don't depend on a Cancel handler for cleanup. Handlers such as
handleCancelonly run when the user clicks your button. - If you need cleanup that must always happen, put it in
disconnectedCallback, which runs whenever the component is removed from the DOM, whatever the reason.
disconnectedCallback() {
// Runs on Cancel, X, Escape and after CloseActionScreenEvent
this.description = '';
}For a simple description editor you rarely need this. It matters when you hold timers, subscriptions, or other resources.
Close does not refresh the page
CloseActionScreenEvent only dismisses the panel. It does not reload the record page. Fields on the page update on their own when you save with updateRecord, because the Lightning Data Service cache is notified. If you changed data some other way, such as an Apex call, the page can show stale values after the panel closes. The chapter on refreshing record data covers that case.
Headless actions have nothing to close
A headless action runs invoke() and finishes. There is no modal, so you don't import CloseActionScreenEvent. Dispatching it from a headless action has no useful effect. If a requirement says "close the action" for a headless action, check whether the requirement really means a screen action.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Dispatching close before `await updateRecord` finishes | No error or success feedback, component destroyed mid-request | Dispatch after the awaited call resolves |
| Closing inside `catch` | User loses their input on a failed save | Show an error toast and keep the panel open |
| Importing the event from the wrong module | `CloseActionScreenEvent` is undefined or the build fails | Import from `lightning/actions` |
| Relying on `handleCancel` for cleanup | Cleanup skipped when the user clicks X or presses Escape | Use `disconnectedCallback` |
| Expecting the close to refresh data | Stale values after an Apex update | Refresh the view explicitly |
| Using the event in a headless action | Nothing happens | Use a screen action if you need a panel |
Testing the close behavior
You can test the close logic with Jest. The event is a normal DOM event dispatched on the host element, so a listener on the element catches it. To avoid hard-coding the event type string, read the type from a new instance.
import { createElement } from 'lwc';
import UpdateDescription from 'c/updateDescription';
import { CloseActionScreenEvent } from 'lightning/actions';
import { updateRecord } from 'lightning/uiRecordApi';
jest.mock('lightning/uiRecordApi', () => ({
updateRecord: jest.fn()
}));
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
function setup() {
const element = createElement('c-update-description', {
is: UpdateDescription
});
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
const closeHandler = jest.fn();
element.addEventListener(new CloseActionScreenEvent().type, closeHandler);
return { element, closeHandler };
}
function clickButton(element, label) {
element.shadowRoot.querySelector(`lightning-button[label="${label}"]`).click();
}
describe('c-update-description closing', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('closes the panel when Cancel is clicked', () => {
const { element, closeHandler } = setup();
clickButton(element, 'Cancel');
expect(closeHandler).toHaveBeenCalledTimes(1);
expect(updateRecord).not.toHaveBeenCalled();
});
it('closes the panel after a successful save', async () => {
updateRecord.mockResolvedValue({});
const { element, closeHandler } = setup();
clickButton(element, 'Save');
await flushPromises();
expect(updateRecord).toHaveBeenCalledTimes(1);
expect(closeHandler).toHaveBeenCalledTimes(1);
});
it('keeps the panel open when the save fails', async () => {
updateRecord.mockRejectedValue({ body: { message: 'Save failed' } });
const { element, closeHandler } = setup();
clickButton(element, 'Save');
await flushPromises();
expect(closeHandler).not.toHaveBeenCalled();
});
});The three tests cover the three exits: cancel, success, and failure. The failure test is the one that guards against the "close inside catch" mistake. If your Jest setup does not provide a stub for lightning/actions, check your @salesforce/sfdx-lwc-jest version or add a manual mock in jest.config.js.
Exercise
A teammate's save handler calls updateRecord, does not await it, and dispatches CloseActionScreenEvent on the next line. Users report that the panel closes but a failed save shows no error. Explain why, and say how to fix it.
Show answer
Without await, the close event runs right after the request starts, before the result is known. The platform destroys the component, so the later error handling has no visible effect and the user never learns the save failed. Fix it by making the handler async, using await updateRecord({ fields }) inside a try block, and dispatching CloseActionScreenEvent only after the awaited call resolves. Show an error toast in the catch block and leave the panel open.
Exercise
Your screen action starts a timer in connectedCallback. Where should you stop it so it is cleared whether the user clicks Cancel, clicks the X, or the save succeeds?
Show answer
Stop it in disconnectedCallback. It runs whenever the component is removed, including after CloseActionScreenEvent and when the platform closes the panel through the X button or Escape. A handleCancel method runs only when the user clicks your own Cancel button.