Article 1 min read Free

Navigation, Toasts & Errors

Use platform services: navigate with NavigationMixin, show toast notifications, and handle errors gracefully.

Advertise with us 728 × 90

Navigation, toasts & errors

Beyond rendering data, real components need to move users around, give feedback, and fail gracefully. Salesforce provides platform modules for each of these so your components behave consistently with the rest of Lightning Experience. The three you'll reach for constantly are NavigationMixin for navigation, ShowToastEvent for notifications, and a solid pattern for surfacing errors.

Navigation uses the NavigationMixin applied to your component's class. You build a page reference — a descriptor of where to go, such as a record page, a list view, a web page, or a component — and pass it to this[NavigationMixin.Navigate](pageRef). This keeps navigation declarative and portable across desktop and mobile.

import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import saveRecord from '@salesforce/apex/AccountController.save';

export default class AccountActions extends NavigationMixin(LightningElement) {
    async handleSave() {
        try {
            const recordId = await saveRecord({ /* ... */ });
            this.showToast('Success', 'Account saved', 'success');
            this[NavigationMixin.Navigate]({
                type: 'standard__recordPage',
                attributes: { recordId, objectApiName: 'Account', actionName: 'view' }
            });
        } catch (error) {
            this.showToast('Error', this.reduceError(error), 'error');
        }
    }

    showToast(title, message, variant) {
        this.dispatchEvent(new ShowToastEvent({ title, message, variant }));
    }

    reduceError(error) {
        return (error?.body?.message) || error?.message || 'Unknown error';
    }
}

Toasts are dispatched by firing a ShowToastEvent with a title, message, and variant (success, error, warning, or info). They're the standard way to confirm an action or report a problem without a modal. Keep messages short and specific.

Error handling deserves care because Apex and wire errors arrive in different shapes. A wire error lands in the adapter's error property; an imperative call rejects a Promise you catch. The messages nest differently — sometimes in error.body.message, sometimes in an array of page errors — so a small reducer like reduceError that normalises them into a readable string is a common, worthwhile utility. Always show the user something meaningful rather than a silent failure. With interactive, resilient components built, it's time to prove they work — testing with Jest is next.

Enjoying this free lesson?

Namaste Salesforce is open and free. A star or a small sponsorship keeps it going.

Swarnil Singhai

Written by

Swarnil Singhai

Building Namaste Salesforce

Discussion