How To Implement Lazy Loading In Lightning Component

How To Implement Lazy Loading In Lightning Component

Lazy loading is a technique that allows you to load data or javascript component asynchronously and increases the performance and data will reflect on the fly.

Lightning Data tables are an enhanced version of an HTML table and are used to display tabular data. Lightning: datatable is not supported on mobile devices also inline editing is currently not supported. Salesforce defines some standard events and Action for the data table. So here I will perform the Lazy loading using standard events in Lightning.

Create @AuraEnabled class ApexControllerLazyComponent.apxc

ApexControllerLazyComponent class will return the list of records according to your query.

public class ApexControllerLazyComponent {

 @AuraEnabled

 public Static list<Opportunity> getOpportunity(Integer Limits){

 return [Select id,Name,AccountId,StageName,CloseDate,Account.Name From Opportunity LIMIT :Integer.valueof(Limits)];

 }

 @AuraEnabled

 public static Integer TotalOpportunity(){

 AggregateResult results = [SELECT Count(Id) TotalOpportunity From Opportunity];

 Integer totalOpportunity = (Integer)results.get(‘TotalOpportunity

 return totalOpportunity;

 }

}

Go to developer console > new >  create a lightning component.

The table will be populated during initialization and the table data is loaded using the init handler. checkboxes select the entire row of data and invoke the onrowselection event handler.

columns attribute will set the header (columns) as I have already defined the fields and assign in columns attribute and data will populate with the help of Opplist attribute.

onrowaction will fire when you click one of any actions which we have defined in columnsandquickactions function in js controller below.\

LazyComponentController.cmp

<aura:component controller=”ApexControllerLazyComponent” implements=”flexipage:availableForAllPageTypes,force:appHostable”>

 <!–handler–>

 <aura:handler name=”init” value=”{!this}” action=”{!c.doInit}”/>

 <!–handler–>

 <!–attribute–>

 <aura:attribute name=”columns” type=”List” />

 <aura:attribute name=”Opplist” type=”object” />

 <aura:attribute name=”initRows” type=”Integer” default=”10″/>

 <aura:attribute name=”Count” type=”Integer” default=”10″/>

 <aura:attribute name=”Offset” type=”Integer” default=”0″/>

 <aura:attribute name=”totalResult” type=”Integer” default=”0″/>

 <aura:attribute name=”locallimit” type=”Integer” default=”0″/>

 <!–attribute–>

 <!–Component–>

 <d iv class=”slds-m-around_xx-small” style=”height: 300px”>

 <lightning:datatable columns=”{!v.columns}”

                      data=”{!v.Opplist}”

                   keyField=”Id”

                      showRowNumberColumn=”true”

                      rowNumberOffset=”0″

                      onrowaction=”{!c.RowAction}”

                      onrowselection=”{!c.handleSelectedRow}”

                      enableInfiniteLoading=”true”

                      loadMoreOffset=”{!v.loadMoreOffset}”

                      onloadmore=”{!c.LoadMore}”/>

 </div>

 <!–Component–>

</aura:component>

enableInfiniteLoading should be true to call onloadmore event so whenever you will scroll, LoadMore action will be triggered and returns the list of records.

you can also take a input from users, how much records will be returned by this function as I have defined Count default 10.

LazyComponentController.js

({

    doInit : function(component, event, helper) {

        helper.columnsandquickactions(component);

        helper.getOpportunityList(component);

        helper.totalopportunity(component);       

},

    handleSelectedRow :function (component, event, helper) {

        var selectedRows = event.getParam(‘selectedRows’);

        var NoofRows = selectedRows.length;

        alert(NoofRows);   

},

    RowAction: function (component, event, helper) {

        var action = event.getParam(‘action’);

        switch (action.name){ 

            case ‘New’: alert(action.name)

            break;

            case ‘edit’:alert(action.name)

            break;

            case ‘delete’: alert(action.name)

            break;

            case ‘view’:alert(action.name)

            break; 

            default: alert(‘Salesforce’);

        }

},

    LoadMore:function (component, event, helper) {

        event.getSource().set(“v.isLoading”, true);

        var recordLimit = component.get(“v.initRows       var action = component.get(“c.getOpportunity action.setParams({

            “Limits”: recordLimit,

        });

        action.setCallback(this, function(response) {          

            var state = response.getState();     

            if (state === “SUCCESS” ) {

                 var Opplist = response.getReturnValue();

                component.set(“v.initRows”,component.get(“v.initRows”)+10vent.getSource().set(“v.isLoading”, false);

                component.set(‘v.Opplistpplist);  

               component.set(“v.locallimit”,Opplist.length }

        });

        if(component.get(‘v.totalResult=component.get(‘v.locallimit

            event.getSource().set(“v.isLoading”, false);

         }

       else{

            $A.enqueueAction(action);

        }

},

})

LazyComponentHelper.js

({

    getOpportunityList : function(component) {

        var action = component.get(“c.getOpportunity       action.setParams({

            “Limits”: component.get(“v.initRows       });

        action.setCallback(this, function(response) {          

           var state = response.getState();

            if (state === “SUCCESS” ) {

                var showToast = $A.get(“e.force:showToast”);

               showToast.setParams({

                    ‘title’ : ‘Load’,

                    ‘message’ : ‘Opportunity Load Sucessfully.’

                });

                showToast.fire();

                var Opplist = response.getReturnValue();

                component.set(“v.Opplist”,Opplist         var nextlimit=component.get(“v.initRows”)+component.get(“v.Count     component.set(“v.initRows”,nextlimit }

        });

        $A.enqueueAction(action);

},

    columnsandquickactions: function(component){

        var actions =[

            {label: ‘New’, name:’New’},

            {label: ‘Edit’,name:’edit’},

            {label: ‘View’ ,name:’view’},

            {label: ‘Delete’, name: ‘delete’}         

        ];

        component.set(‘v.columns            {label:’Name’,fieldName:’Name’, type:’text’,shortable:true},

            {label:’Account Name’, fieldName:’AccountId’, type:’Account Name’,shortable:true},

            {label: ‘Phone’, fieldName: ‘Phone’, type: ‘phone’},

            {label: ‘Stage’, fieldName:’StageName’, type:’text’},

            {label: ‘Close Date’, fieldName:’CloseDate’, type:’text’},

            {type:’action’, typeAttributes:{

               rowActions:actions

            }}

        ]);

},

   totalopportunity : function(component) {

        var action = component.get(“c.TotalOpportunity       action.setCallback(this, function(response) {

            var state = response.getState();

            if (state === “SUCCESS” ) {

                var resultData = response.getReturnValue();

                component.set(“v.totalResultsultData);

            }

        });

        $A.enqueueAction(action);

},

})

Final Lightning datatable will look like :