Sub topic 9
Telling the user what happened with toasts
A quick action runs and then disappears. The panel closes, or a headless action never showed anything. The user gets no signal that the save worked unless the component sends one. A toast is a short message that appears at the top of the page, and ShowToastEvent is how an LWC raises one. This chapter covers building toasts, choosing their variant and mode, reporting errors from updateRecord, ordering toasts relative to closing the panel, and testing the result with Jest.
This chapter assumes you can read the UpdateDescription screen action from the earlier chapters. It also assumes you know how dispatchEvent works in LWC and can run basic Jest tests in a Salesforce DX project.
How a toast reaches the screen
You don't render a toast in your own template. The component dispatches a ShowToastEvent, and Lightning Experience listens for it and draws the message. Nothing needs to be added to your HTML.
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
this.dispatchEvent(new ShowToastEvent({
title: 'Success',
message: 'Description updated',
variant: 'success'
}));The constructor takes one object. These are the properties you will use most.
| Property | Purpose | Values |
|---|---|---|
| `title` | Bold heading of the toast | Any string |
| `message` | Body text | Any string. May contain `{0}`, `{1}` placeholders |
| `variant` | Color and icon | `info` (default), `success`, `warning`, `error` |
| `mode` | How long it stays | `dismissible` (default), `pester`, `sticky` |
| `messageData` | Values for placeholders, including links | Array of strings or `{ url, label }` objects |
Choosing a variant
The variant tells the user how to read the result before they read the text. Use it consistently.
success: the work finished. Use it afterupdateRecordresolves.error: the work failed and the user may need to act.warning: the work finished, but something needs attention, such as a partial update.info: neutral news, such as "No changes to save".
Choosing a mode
The mode controls how long the toast stays on screen and whether the user can close it.
dismissibleis the default. The toast shows a close button and disappears after about three seconds.pesterremoves the close button. The toast still disappears on its own.stickystays until the user closes it.
Success messages are fine with the default, because the user only needs a glance. Error messages deserve sticky, because three seconds is too short to read a server error and decide what to do.
Linking to a record from a toast
A message can contain a link when you use placeholders and messageData. The {0} in the message is replaced by the first item in the array. If the item is an object with url and label, it renders as a link.
this.dispatchEvent(new ShowToastEvent({
title: 'Success',
message: 'Updated {0}',
messageData: [
{
url: '/lightning/r/Account/' + this.recordId + '/view',
label: 'this account'
}
],
variant: 'success'
}));This is useful in global actions that create records, where the user is not on the new record's page. For a record action that stays on the same page, a plain message is usually enough.
Reporting errors from updateRecord
When updateRecord fails, it rejects with an error object. The user-readable text is usually in error.body.message. That is what the screen action from earlier chapters uses:
message: error?.body?.message || 'Unknown error'Some failures carry more detail. Validation rules, required fields, and field-level security problems can appear in error.body.output, as output.errors, output.fieldErrors, or both. A failed validation rule often has a generic top-level message ("An error occurred while trying to update the record") while the useful text sits deeper. A small helper keeps the handler readable and covers the common shapes.
export function reduceError(error) {
if (!error) {
return 'Unknown error';
}
if (typeof error === 'string') {
return error;
}
const body = error.body;
if (body && body.output) {
const messages = [];
(body.output.errors || []).forEach((e) => messages.push(e.message));
Object.values(body.output.fieldErrors || {}).forEach((list) =>
list.forEach((e) => messages.push(e.message))
);
if (messages.length) {
return messages.join(' ');
}
}
if (body && typeof body.message === 'string') {
return body.message;
}
return error.message || 'Unknown error';
}Put this helper in a shared module, for example c/errorUtils, so every quick action reports errors the same way. Then the catch block becomes:
import { reduceError } from 'c/errorUtils';
// inside handleSave
} catch (error) {
this.dispatchEvent(new ShowToastEvent({
title: 'Error updating record',
message: reduceError(error),
variant: 'error',
mode: 'sticky'
}));
}Order of events in a screen action
A screen action has two jobs after the save: tell the user, and close the panel. Both are events dispatched from your component, so the order in your code is the order they fire.
Do not use the fence above. The diagram follows.
Two decisions in this flow matter.
- Toast first, then close. Dispatch the toast before
CloseActionScreenEvent. The toast is handled by the page, not by your component, so it stays visible after the panel is gone. Doing it in this order also means the component is still alive when the event is dispatched. - Keep the panel open on failure. If the save fails, the user's typed text is still in the textarea. Closing the panel would throw that text away. Leaving it open with an error toast lets them fix the value and click Save again. The
finallyblock re-enables the button either way.
Toasts in a headless action
A headless action has no panel, so the toast is the whole user interface. If invoke() does work and shows nothing, the user cannot tell whether the click did anything. The example from the earlier chapter shows the minimum:
@api invoke() {
this.dispatchEvent(new ShowToastEvent({
title: 'Action ran',
message: 'Record ' + this.recordId + ' was processed',
variant: 'success'
}));
}When invoke() does asynchronous work, wrap it in try/catch and send an error toast from the catch block. An unhandled rejection in a headless action leaves the user with no message at all, and the failure shows up only in the browser console.
Common pitfalls
- Toast text that is too technical. Raw messages such as
FIELD_CUSTOM_VALIDATION_EXCEPTIONmean little to users. Prefer the text your validation rule defines, and put the failing step in the title. - Non-string messages.
messagemust be a string. Passing the error object itself shows[object Object]. - Success toast before the promise settles. Dispatching the toast right after calling
updateRecordwithoutawaitreports success even when the save fails. - Forgetting the
finallyreset. IfisSavingstaystrueafter an error, the Save button stays disabled and the user must cancel and reopen the action. - Toasts outside Lightning Experience. The toast event is handled by the Lightning Experience and Salesforce mobile app containers. Do not rely on it for components used in other containers, where it may be ignored, so check the target environment first.
- Stacking several toasts. Dispatching one toast per field error floods the screen. Join the messages into one toast, as
reduceErrordoes.
Testing toasts with Jest
Because ShowToastEvent is a DOM event, a Jest test can listen for it on the component element. The sfdx-lwc-jest stub for lightning/platformShowToastEvent creates an event named lightning__showtoast, with your parameters in event.detail.
This test mocks updateRecord, clicks Save, and checks the toast.
import { createElement } from 'lwc';
import UpdateDescription from 'c/updateDescription';
import { updateRecord } from 'lightning/uiRecordApi';
jest.mock(
'lightning/uiRecordApi',
() => ({ updateRecord: jest.fn() }),
{ virtual: true }
);
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 toasts = [];
element.addEventListener('lightning__showtoast', (e) => toasts.push(e.detail));
return { element, toasts };
}
function clickSave(element) {
element.shadowRoot.querySelector('lightning-button[label="Save"]').click();
}
describe('c-update-description toasts', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('shows a success toast when the save works', async () => {
updateRecord.mockResolvedValue({});
const { element, toasts } = setup();
clickSave(element);
await flushPromises();
expect(toasts).toHaveLength(1);
expect(toasts[0].variant).toBe('success');
});
it('shows an error toast when the save fails', async () => {
updateRecord.mockRejectedValue({ body: { message: 'Validation failed' } });
const { element, toasts } = setup();
clickSave(element);
await flushPromises();
expect(toasts).toHaveLength(1);
expect(toasts[0].variant).toBe('error');
expect(toasts[0].message).toBe('Validation failed');
});
});The two tests cover both branches of the flow in the diagram. Checking variant and message is enough. Do not assert on exact title wording unless the wording is a requirement, because it makes tests fragile when copy changes.
Exercise
In the Save handler of a screen action, why should the error toast use variant: 'error' and mode: 'sticky', and why should the panel stay open after the error?
Show answer
The error variant marks the result as a failure, and sticky keeps the toast on screen until the user closes it, so they have time to read the message. The panel stays open so the text the user typed is not lost, and they can correct it and click Save again. The finally block resets isSaving so the Save button works for the retry.
Exercise
A teammate's headless action calls an asynchronous helper inside invoke() and has no try/catch. What happens to the user when the helper fails, and how do you fix it?
Show answer
The user sees nothing, because a headless action has no panel and an unhandled rejection only logs to the console. Wrap the call in try/catch (or await it inside an async function with try/catch) and dispatch a ShowToastEvent with variant: 'error' from the catch block, using a helper such as reduceError to build the message.