Submission, Loading States, and Toast Notifications
By the end of this lesson, you'll be able to:
- Manage a loading/submitting state during an async form submission
- Show success and error feedback using ShowToastEvent
- Reset submission state reliably regardless of outcome
Prerequisites: "Validation and reportValidity()"
Loading States
isSubmitting = false;
async handleSubmit() {
this.isSubmitting = true;
try {
await createRecord(recordInput);
} finally {
this.isSubmitting = false;
}
}
<lightning-button label="Submit" onclick={handleSubmit} disabled={isSubmitting}></lightning-button>
<template if:true={isSubmitting}>
<lightning-spinner alternative-text="Submitting"></lightning-spinner>
</template>
Using finally (Module 4) guarantees isSubmitting resets whether the submission succeeds or throws — without it, a failed submission would leave the button permanently disabled.
Toast Notifications with ShowToastEvent
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
showSuccessToast() {
this.dispatchEvent(new ShowToastEvent({
title: 'Success',
message: 'Record created successfully.',
variant: 'success',
}));
}
showErrorToast(message) {
this.dispatchEvent(new ShowToastEvent({
title: 'Error creating record',
message,
variant: 'error',
}));
}
ShowToastEvent is a special, framework-provided event type — dispatched like the CustomEvents from Module 5, but automatically caught and rendered as a toast notification by the Lightning Experience shell, with no listener needed on any parent component.
A Worked Example
async handleSubmit() {
this.isSubmitting = true;
try {
await createRecord(recordInput);
this.showSuccessToast();
} catch (error) {
this.showErrorToast(error.body?.message ?? 'An unexpected error occurred.');
} finally {
this.isSubmitting = false;
}
}
Loading state, success feedback, and error feedback, all handled in one cohesive try/catch/finally block.
Exercise
Write a showErrorToast method that dispatches a ShowToastEvent with variant "error", title "Save Failed", and a message parameter.
Show hint
Follow the pattern shown above.
Exercise
Challenge: explain, as a comment, why isSubmitting is reset inside a finally block rather than at the end of the try block.
Show hint
Think about what happens on the error path.
Submission, Loading States, and Toast Notifications Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A polished form gives clear feedback during and after submission — a disabled button and spinner while work is in progress, and a toast notification once it resolves.