
Introduction:
In this post, we will explore how to build a Lazy Loading Table using Lightning Web Components (LWC) in Salesforce. Lazy loading allows us to load data dynamically as the user scrolls, providing a smooth and efficient user experience. We’ll implement a table, load more data as the user reaches the bottom of the table. Let’s dive into the code and understand how it works.
Code / Explanation:
The code consists of three files: <strong>lazyLoadingTable.html</strong>
, <strong>lazyLoadingTable.js</strong>
, and <strong>lazyLoadingTable.css</strong>
. Let’s break down each file and its functionality.
<template> | |
<lightning-card title="Lazy Loading Table"> | |
<div class="table-container" onscroll={handleScroll}> | |
<div class="scrollable-table"> | |
<lightning-datatable | |
key-field="Id" | |
data={visibleData} | |
columns={tableColumns} | |
class="fixed-header" | |
hide-checkbox-column="true"> | |
</lightning-datatable> | |
</div> | |
<template if:true={isLoading}> | |
<div class="loading-spinner"> | |
<lightning-spinner alternative-text="Loading" size="medium"></lightning-spinner> | |
</div> | |
</template> | |
</div> | |
</lightning-card> | |
</template> |
The HTML template defines the structure of the component. We use the lightning-card
component as the container. Inside it, we have a div
with a class of <strong>table-container</strong>
for scrollable content. The div
contains a div
with a class of scrollable-table
, which is responsible for scrolling the table content. We use the <strong>lightning-datatable</strong>
component to display the table with the specified columns and data. We also include a loading spinner using lightning-spinner
component inside a template <strong>if:true={isLoading}</strong>
block.
import { LightningElement } from 'lwc'; | |
import getContactRecords from '@salesforce/apex/LazyLoadingController.getContactRecords'; | |
const PAGE_SIZE = 10; | |
export default class LazyLoadingTable extends LightningElement { | |
tableColumns = [ | |
{ label: 'Name', fieldName: 'Name', type: 'text' }, | |
{ label: 'Phone', fieldName: 'Phone', type: 'phone' }, | |
{ label: 'Email', fieldName: 'Email', type: 'email' } | |
]; | |
visibleData = []; | |
isLoading = false; | |
currentPage = 0; | |
totalRecords = 0; | |
connectedCallback() { | |
this.loadMoreData(); | |
} | |
handleScroll(event) { | |
const target = event.target; | |
if (target.scrollHeight - target.scrollTop <= target.clientHeight) { | |
this.loadMoreData(); | |
} | |
} | |
loadMoreData() { | |
if (this.isLoading) { | |
return; // Prevent multiple simultaneous calls | |
} | |
this.isLoading = true; | |
this.currentPage++; | |
getContactRecords({ pageSize: PAGE_SIZE, page: this.currentPage }) | |
.then((data) => { | |
if (data && data.contacts.length > 0) { | |
this.visibleData = [...this.visibleData, ...data.contacts]; | |
} | |
}) | |
.catch((error) => { | |
console.error('Error fetching more contact records:', error); | |
}) | |
.finally(() => { | |
this.isLoading = false; | |
}); | |
} | |
} |
The JavaScript file handles the logic of the Lazy Loading Table component. We define the <strong>tableColumns</strong>
array to specify the columns for the table. The <strong>visibleData</strong>
array holds the data currently visible in the table. The <strong>isLoading</strong>
flag tracks whether data is being loaded. The <strong>currentPage</strong>
variable keeps track of the current page number, and <strong>totalRecords</strong>
stores the total number of records.
In the <strong>connectedCallback</strong>
lifecycle hook, we load the initial data by calling the <strong>loadMoreData</strong>
method.
The <strong>handleScroll</strong>
method is triggered when the user scrolls within the table container. It checks if the user has reached the bottom of the table, and if so, calls the <strong>loadMoreData</strong>
method.
The <strong>loadMoreData</strong>
method performs the lazy loading functionality. It checks if data is already being loaded (<strong>isLoading</strong>
flag) to prevent multiple simultaneous calls. It increments the <strong>currentPage</strong>
variable, calls the Apex method <strong>getContactRecords</strong>
to fetch the next set of data, and updates the <strong>visibleData</strong>
array accordingly. Any errors are logged to the console, and the isLoading
flag is reset once the data is loaded.
.table-container { | |
height: 300px; | |
overflow-y: auto; | |
} | |
.scrollable-table { | |
height: fit-content; | |
} | |
The CSS file contains styles to control the appearance of the table. The .
table-container
class sets the height and enables vertical scrolling. The .<strong>scrollable-table</strong>
class adjusts the height of the table content. These styles ensure that the table stays within the specified height and enables scrolling when necessary.
public with sharing class LazyLoadingController { | |
@AuraEnabled(cacheable=true) | |
public static Map<String, Object> getContactRecords(Integer pageSize, Integer page) { | |
Integer offset = Math.max(0, (page - 1) * pageSize); | |
List<Contact> contacts = [SELECT Id, Name, Email, Phone FROM Contact ORDER BY Name ASC LIMIT :pageSize OFFSET :offset]; | |
Integer totalRecords = [SELECT COUNT() FROM Contact]; | |
Map<String, Object> result = new Map<String, Object>(); | |
result.put('contacts', contacts); | |
result.put('totalRecords', totalRecords); | |
return result; | |
} | |
} |
Demo
Conclusion
In this blog post, we learned how to build a Lazy Loading Table using Lightning Web Components (LWC) in Salesforce. We implemented a table, loaded data dynamically as the user scrolled. The code provided allows for efficient loading of data, providing a better user experience while minimizing the impact on performance.
By implementing lazy loading, we can handle large datasets more efficiently, reducing initial loading time and improving overall performance.
Implementing this solution can greatly benefit applications that deal with large datasets and require efficient data presentation. It allows users to interact with the data more effectively and provides a seamless experience.
Remember to optimize your Apex code for fetching data efficiently and handle pagination and sorting if required. This will ensure optimal performance and a smooth user experience.
By following this approach, you can create a powerful and efficient Lazy Loading Table in Salesforce using Lightning Web Components.
I hope this blog post helps you in building your own Lazy Loading Table in Salesforce using Lightning Web Components. Happy coding!
About the blog
SFDCLessons is a blog where you can find various Salesforce tutorials and tips that we have written to help beginners and experienced developers alike. we also share my experience and knowledge on Salesforce best practices, troubleshooting, and optimization. Don’t forget to follow us on:
Newsletter
Subscribe to our email newsletter to be notified when a new post is published.