Lightning Web Components

Lightning Web Components:Spinners and Toast Messages in LWC

In this post, we are going to discuss about how we can use spinners and toast messages in lightning web components.

Spinners in LWC

Adding a spinner in LWC is very easy. We can using standard lightning -spinner for this purpose.

We juts have to add following code in out html file :

• Add the following code in HTML file of your component :

<template if:true={loading}>
	<div class="spinner">
		<lightning-spinner alternative-text="Loading"></lightningspinner>
            </div>
 </template>

We need to include this lightning spinner into our HTML file and wrap this spinner using some boolean variable so that you can switch on and off this
spinner as an when required.

Toast Messages in LWC

We have standard event – showToastEvent from platformShowToastEvent library in LWC which we can use for displaying toast messages in lightning web components.

Import standard platform toast event in js file:

import {ShowToastEvent} from 'lightning/platformShowToastEvent’;

• Create Instance of ShowToastEvent with desired parameters :

const toastEvent  = new ShowToastEvent({
                	title :'Success!',
                	message:'Contact List Updated',
              	 variant:'success',
                	mode:'dismissable’
          	});

Paramters for toast messages include:

title(String) – It refers to title of toast messages displayed as header.

message(String) – Its a string containing message for user.

variant(String) – Theme and icon displayed on toast messages. Variant can be:

info – grey toast with info icon. It is the default variant set. success – A green toast with check mark icon. error – A red toast with an error icon. warning – A yellow toast with a warning icon.

mode(String) – Mode decides the behaviour/Persistence of toast message.

dismissable – Remains visible for 3 sec or untill user clicks close button. pester – Remains visible for 3 sec. sticky – Remains visible till user clicks on close button.

Dispatch the event when required

this.dispatchEvent(toastEvent);

Lets implement this:

We will create a lightning component say “ContactlistCmp”. We will create a lightning button, onclick of which we will make server call and fetch list of contacts to display on browser. While fetching the contact lists, spinner will be displayed and once contact list is fetched and displayed successfully,spinner disappears and success toast message is displayed.

ContactlistCmp.html

<template>

    <template for:each={conList} for:item="contact">
        <lightning-card key = {contact.LastName} icon-name="standard:contact">
            <p>{contact.LastName}</p>
        </lightning-card>
    </template> 

   <lightning-button label="get Contacts" onclick = {getcontactLists}></lightning-button>
   
   <template if:true={loading}>
    <div class= "spinner">
        <lightning-spinner alternative-text="Loading"></lightning-spinner>
    </div>
   </template>
   
</template>

ContactlistCmp.js

/* eslint-disable no-console */
import { LightningElement,track} from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
import getContactList from '@salesforce/apex/contactListCtrl.getContactList';

export default class ContactlistCmp extends LightningElement {
    @track conList;
    @track loading = false;
    /* Using Imperative CAll */

    getcontactLists(){
        this.loading = true;
        getContactList().then(result=>{
            this.conList = result;
            this.loading = false;
            const toastEvent = new ShowToastEvent({
                title : 'Success !',
                message : 'Contact List Updated Successfully',
                variant: 'success',
                mode : 'dismissable'
            });
            this.dispatchEvent(toastEvent);
        })
        .catch(error=>{
            console.log('error#'+error);
            this.loading = false;
            const toastEvent = new ShowToastEvent({
                title : 'Error !',
                message : 'Error Occurred',
                variant: 'error',
                mode : 'dismissable'
            });
            this.dispatchEvent(toastEvent);
        })
    }

}

ContactlistCmp.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>47.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>
    lightning__HomePage
    </target>
    </targets>
</LightningComponentBundle>

Lets include this conponent into Lightning home page. If you click on “get Contacts” button following screens will appear.

Spinner when server call is in progress

Toast message once, contact list is fetched and displayed successfully.

Remember, lightning standard spinner and toast messages does not work in salesforce classic.

So , we will wrap up this post here . Stay tuned for next posts !

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s