Lightning Component – Add a Spinner while loading
One of the coolest things about building Lightning components is that they are single page apps so they user can receive feedback without leaving the page.
Recently, I built a component that displayed a table of data from a search but I wanted the user to know that the data was refreshing if they did a second search. I was about to build something custom when I realised that there is a standard Lightning component that does this!
I added the following code to my component. This code means that anytime its is waiting for a response – the spinner will show. You can also controller this from a button press until the results are generated if you have a more complex use case.
[sourcecode type=”plaintext”]
<aura:handler event="aura:waiting" action="{!c.showSpinner}"/>
<aura:handler event="aura:doneWaiting" action="{!c.hideSpinner}"/>
[/sourcecode]
and the the following line where I wanted to display the Spinner in the component
[sourcecode type=”plaintext”]
<ui:spinner aura:id="spinner" isVisible="False" />
[/sourcecode]
Then I added the following code to my javascript controller in the Lightning component.
[sourcecode type=”plaintext”]
showSpinner : function (component, event, helper) {
var spinner = component.find(‘spinner’);
var evt = spinner.get("e.toggle");
evt.setParams({ isVisible : true });
evt.fire();
},
hideSpinner : function (component, event, helper) {
var spinner = component.find(‘spinner’);
var evt = spinner.get("e.toggle");
evt.setParams({ isVisible : false });
evt.fire();
}
[/sourcecode]
With all of this, the spinner displays while it is waiting. In my scenario it displays when I am waiting for the data from the apex controller.
I found this useful in two ways:
1. The user knows that something is happening so don’t refresh the page etc
2. If the user does a second search on the page, they know for certain when the results have been updated.