Lazy Data Loading
- Lazy loading helps with loading only the necessary piece and delaying the loading of the remaining until the user needs it, as opposed to bulk loading, which loads all of the data and renders it to the user at once.
- Attributes:
- Using the enable-infinite-loading option, you can load a portion of the data and then display more as viewers scroll to the table's finish. To retrieve extra data, use the onloadmore event handler.
- load-more-offset: Calculates the number of pixels the table's scroll position is from the bottom of the table to determine when to start infinite loading. 20 is the default.
- Visit Salesforce Document Link to understand more about Lightning data Table https://developer.salesforce.com/docs/component-library/bundle/lightning-datatable/documentation
Implementing Lazy Data Load for contact
public with sharing class LazyLoadingController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContact(Integer limitSize, Integer offset){
List<Contact> contactList = [SELECT Id,Name
FROM Contact
ORDER BY CreatedDate
LIMIT :limitSize
OFFSET :offset
];
return contactList;
}
}
lazyLoadingLWCDemo
<template>
<div style="height:500px">
<lightning-datatable key-field="Id"
data={contacts}
columns={columns}
enable-infinite-loading
onloadmore={loadMoreData}
hide-checkbox-column="true"
show-row-number-column="true">
</lightning-datatable>
</div>
</template>
lazyLoadingLWCDemo,js
import { LightningElement} from 'lwc';
import getContact from '@salesforce/apex/LazyLoadingController.getContact';
const columns = [
{ label: 'Id', fieldName: 'Id', type: 'text' },
{ label: 'Name', fieldName: 'Name', type: 'text'}
];
export default class LazyLoadingLWCDemo extends LightningElement {
contacts=[];
error;
columns = columns;
rowLimit =25;
rowOffSet=0;
connectedCallback() {
this.loadData();
}
loadData(){
return getContact({ limitSize: this.rowLimit , offset : this.rowOffSet })
.then(result => {
let updatedRecords = [...this.contacts, ...result];
this.contacts = updatedRecords;
this.error = undefined;
})
.catch(error => {
this.error = error;
this.contacts = undefined;
});
}
loadMoreData(event) {
const currentRecord = this.contacts;
const { target } = event;
target.isLoading = true;
this.rowOffSet = this.rowOffSet + this.rowLimit;
this.loadData()
.then(()=> {
target.isLoading = false;
});
}
}
XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>48.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>