Infinite/lazy loading In LWC Lightning Datatable

by Rijwan Mohmmed
infinite-lazy-loading-in-lwc-lightning-datatable-techdicer

Hello friends, we will discuss how to show Infinite/lazy loading In LWC Lightning Datatable. That way we don’t need pagination and by scrolling, we will load the following data in the LWC Datatable. Here We will load the data on the Client Side.

Also, check this: Pass value from child LWC to parent AURA component

lightning-datatable-infinite--lazy-loading-in-lwc-output-techdicer
lightning-datatable-infinite–lazy-loading-in-lwc-output-techdicer

Key Highlights:

  1. Load the data on scroll.
  2. Save extra space for the pagination button.
  3. More user-friendly.
  4. Load data on the Client-Side.

Code :

LWCLazyLoadingCtrl.cls :

public class LWCLazyLoadingCtrl {    
    @AuraEnabled
    public static List<Account> getAccountData() {
        return [SELECT Id, Name, Type, Phone, CreatedDate FROM Account LIMIT 50000];
    }
 }

lWCLazyLoading.HTML :

<template>
	<!-- create card -->
	<lightning-card variant="Narrow" title="LWC Datatable Infinite/Lazy Loading" icon-name="standard:recipe">
		<div class="slds-var-p-around_small" style="height: 400px;">
			<lightning-datatable key-field="Id" data={data} columns={columns} load-more-offset="20"
				onloadmore={handleLoadMore} enable-infinite-loading hide-checkbox-column show-row-number-column>
			</lightning-datatable>
		</div>
	</lightning-card>	
		
 </template>

lWCLazyLoading.JS :

import { LightningElement } from 'lwc';
import getAccountData from '@salesforce/apex/LWCLazyLoadingCtrl.getAccountData';
const columns = [
    {
        label: 'Account Name', fieldName: 'linkAccount', type: 'url',
        typeAttributes: {
            label: { fieldName: 'Name' },
            target: '_blank'
        }
    },
    { label: 'Type', fieldName: 'Type', type: 'text' },
    { label: 'Phone', fieldName: 'Phone', type: 'text' },
    { label: 'Created Date', fieldName: 'CreatedDate', type: 'date',
            typeAttributes: {
            day: "numeric",
            month: "numeric",
            year: "numeric"
        } 
    }
 ];
 export default class LWCLazyLoading extends LightningElement {
    columns = columns;
    data = [];
    items = [];
    error;
    totalNumberOfRows = 100; // stop the infinite load after this threshold count
    recordCount = 20;
    loadMoreStatus;
    totalRecountCount = 0;
    targetDatatable; // capture the loadmore event to fetch data and stop infinite loading
    connectedCallback() {
        this.getData();
    }
    getData(){
        getAccountData({})
        .then(result => {
            result = JSON.parse(JSON.stringify(result));
            result.forEach(record => {
                record.linkAccount = '/' + record.Id;
            });
            this.totalRecountCount = result.length;
            this.items = [...this.items, ...result];
            this.data = this.items.slice(0, this.recordCount); 
            this.error = undefined;
        }).catch(error => {
            this.error = error;
            this.data = undefined;
            this.items = undefined;
        });
    }
    getRecords() {
        this.recordCount = (this.recordCount > this.totalRecountCount) ? this.totalRecountCount : this.recordCount; 
        this.data = this.items.slice(0, this.recordCount);
        this.loadMoreStatus = '';
        if (this.targetDatatable){
            this.targetDatatable.isLoading = false;
        }
    }
    // Event to handle onloadmore on lightning datatable markup
    handleLoadMore(event) {
        event.preventDefault();
        // increase the record Count by 20 on every loadmore event
        this.recordCount = this.recordCount + 20;
        //Display a spinner to signal that data is being loaded
        event.target.isLoading = true;
        //Set the onloadmore event taraget to make it visible to imperative call response to apex.
        this.targetDatatable = event.target;
        //Display "Loading" when more data is being loaded
        this.loadMoreStatus = 'Loading';
        // Get new set of records and append to this.data
        this.getRecords();
    }
 }

Output:

lightning-datatable-infinite--lazy-loading-in-lwc-output-techdicer
Infinite / lazy loading In LWC Lightning Datatable-output-techdicer

Reference:

  1. LWC datatable

What’s your Reaction?
+1
0
+1
1
+1
1
+1
0
+1
0
+1
0

You may also like

5 comments

Manish April 19, 2023 - 6:44 am

this approach is not working

Reply
Rijwan Mohmmed April 19, 2023 - 5:18 pm

Hi @Manish, What issue you are facing ?

Reply
Rahul September 1, 2023 - 11:00 am

It’s working for me.
Thanks, Rijwan. You are a champ!

Reply
Naveen November 5, 2023 - 6:42 am

This approach causing problem when the screen is loaded

Reply
Asfandyar November 26, 2023 - 6:55 pm

This approach is getting failed when I am using search filters like date range and another text filter. and also when the first time the records are loaded, the lazy loading is not working

Reply

Leave a Comment