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.
<aura:handler event="aura:waiting" action="{!c.showSpinner}"/> <aura:handler event="aura:doneWaiting" action="{!c.hideSpinner}"/>
and the the following line where I wanted to display the Spinner in the component
<ui:spinner aura:id="spinner" isVisible="False" />
Then I added the following code to my javascript controller in the Lightning component.
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(); }
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.