Create dynamic datatable in lightning web component.

Posted on January 15, 2021 Post Thumbnail

Hi Trailblazers, In this Blog Post, We are going to create a dynamic data table in the lightning web component.

Check the following image for the data table.

Data Table

Requirement :)

We need to create a Datatable in LWC in which First we have to show 5 Accounts.

After clicking on SHOW MORE  button, We need to show more Accounts.

And clicking on SHOW LESS button, We need to show 5 Accounts.

We have 2 Solutions for this requirement.

In both Solutions,

We are going to use Lightning Datatable for creating Table and Wire Adaptor for getting accounts.

Let's have a look at both solutions one by one.

1st Solution:

We need to create a class with 2 methods that return Accounts based on Query Limit.

On each button click, We have to call Apex methods.

This component also fulfil our requirement, but It calls Server on each button click.

It's not the best solution.

Check the following component.

Apex Class

public with sharing class AccountHelper {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList() {
        return [SELECT Id, Name, Type, Rating,
                Phone, Website, AnnualRevenue
            FROM Account LIMIT 5];
    }
    @AuraEnabled(cacheable=true)
    public static List<Account> getNewAccountList(Integer lim) {
        return [SELECT Id, Name, Type, Rating,
                Phone, Website, AnnualRevenue
            FROM Account LIMIT : lim];
    }

}

Component HTML

<template>
<div class="slds-box outerDesign">
    <h1> Account Datatable</h1>
    <lightning-button label="SHOW LESS" title="Non-primary action" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
    <lightning-button label="SHOW MORE" title="Non-primary action" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
</div>
<div class="slds-box design">
<template if:true={accList}>
    <lightning-datatable data={accList} columns={columns} key-field="Id">
    </lightning-datatable>
</template>
<template if:true={error}>
    {error}
</template>
</div>
</template> 

Component JS

import { LightningElement ,api, wire, track} from 'lwc';
import getAccountList from '@salesforce/apex/AccountHelper.getAccountList';
import getNewAccountList from '@salesforce/apex/AccountHelper.getNewAccountList';
export default class LightningDatatableLWCExample extends LightningElement {
    @track columns = [{
            label: 'Account name',
            fieldName: 'Name',
            type: 'text',
            sortable: true
        },
        {
            label: 'Type',
            fieldName: 'Type',
            type: 'text',
            sortable: true
        },
        {
            label: 'Annual Revenue',
            fieldName: 'AnnualRevenue',
            type: 'Currency',
            sortable: true
        },
        {
            label: 'Phone',
            fieldName: 'Phone',
            type: 'phone',
            sortable: true
        },
        {
            label: 'Website',
            fieldName: 'Website',
            type: 'url',
            sortable: true
        },
        {
            label: 'Rating',
            fieldName: 'Rating',
            type: 'test',
            sortable: true
        }
    ];
 
    @track error;
    @track accList ;
    @wire(getAccountList)
    wiredAccounts({
        error,
        data
    }) {
        if (data) {
            console.log(data);
            console.log('Required Length');
            console.log(Object.keys(data).length);
            console.log(Object.keys(data));
            this.accList = data;
        } else if (error) {
            this.error = error;
        }
    }
    handleClick(event) {
        var lim;
        if(event.target.label ==='SHOW MORE')
            lim = 20 ;
        if(event.target.label ==='SHOW LESS')
            lim = 5;

    
        getNewAccountList({lim}).then(result =>{
           //console.log(JSON.parse(result));
           this.accList = result ;
            console.log('Object Returned');
            //this.initialiseFullCalendarJs();
            this.error = undefined;
        })
        .catch(error => {
            console.log(error);
            console.log('error');
            this.error = error;
            //this.outputResult = undefined;
        });
  }
    
}

Component XML

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Component CSS

.design
{
    background-color:rgb(228 245 237 / 48%);
    text-align: center;
    padding: 40px;
}
.outerDesign
{
    text-align: center;
    background-color:rgb(0 156 219 / 20%);
}
h1
{
    color: white;
    text-align: center;
    font-size: 150%;
    background-color:rgb(0 156 219 / 20%);
}

The result of the above component is:

Result

2nd Solution

In the second Solution, We Query all accounts once and store them in a JS array.

And we perform all calculations on the Client side.

Check the following Component.

Apex Class

public with sharing class AccountHelper {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList() {
        return [SELECT Id, Name, Type, Rating,
                Phone, Website, AnnualRevenue
            FROM Account];
    }
}

Component HTML

<template>
<div class="slds-box outerDesign">
    <h1> Account Datatable</h1>
    <lightning-button label="SHOW LESS" title="Non-primary action" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
    <lightning-button label="SHOW MORE" title="Non-primary action" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
</div>
<div class="slds-box design">
<template if:true={accList}>
    <lightning-datatable data={accList} columns={columns} key-field="Id">
    </lightning-datatable>
</template>
<template if:true={error}>
    {error}
</template>
</div>
</template> 

Component JS

import { LightningElement ,api, wire, track} from 'lwc';
import getAccountList from '@salesforce/apex/AccountHelper.getAccountList';
import getNewAccountList from '@salesforce/apex/AccountHelper.getNewAccountList';
export default class LightningDatatableLWCExample extends LightningElement {
    @track columns = [{
            label: 'Account name',
            fieldName: 'Name',
            type: 'text',
            sortable: true
        },
        {
            label: 'Type',
            fieldName: 'Type',
            type: 'text',
            sortable: true
        },
        {
            label: 'Annual Revenue',
            fieldName: 'AnnualRevenue',
            type: 'Currency',
            sortable: true
        },
        {
            label: 'Phone',
            fieldName: 'Phone',
            type: 'phone',
            sortable: true
        },
        {
            label: 'Website',
            fieldName: 'Website',
            type: 'url',
            sortable: true
        },
        {
            label: 'Rating',
            fieldName: 'Rating',
            type: 'test',
            sortable: true
        }
    ];
 
    @track error;
    @track accList ;
    allAcc;
    someAcc;
    @wire(getAccountList)
    wiredAccounts({
        error,
        data
    }) {
        if (data) {
            console.log(data);
            console.log('Required Length');
            console.log(Object.keys(data).length);
            console.log(Object.keys(data));
            this.allAcc = data;
            this.accList = data.slice(0,5);
        } else if (error) {
            this.error = error;
        }
    }
    handleClick(event) {
        var lim;
        if(event.target.label ==='SHOW MORE')
            this.accList = this.allAcc ;
        if(event.target.label ==='SHOW LESS')
            this.accList = this.allAcc.slice(0,5);

        /*
        getNewAccountList({lim}).then(result =>{
           //console.log(JSON.parse(result));
           this.accList = result ;
            console.log('Object Returned');
            //this.initialiseFullCalendarJs();
            this.error = undefined;
        })
        .catch(error => {
            console.log(error);
            console.log('error');
            this.error = error;
            //this.outputResult = undefined;
        });
        */
  }
    
}

Component XML

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Component CSS

.design
{
    background-color:rgb(228 245 237 / 48%);
    text-align: center;
    padding: 40px;
}
.outerDesign
{
    text-align: center;
    background-color:rgb(0 156 219 / 20%);
}
h1
{
    color: white;
    text-align: center;
    font-size: 150%;
    background-color:rgb(0 156 219 / 20%);
}

We need to keep in mind to reduce Apex Method calls.

The result of the above component is:

Result

As you can see, It's working now.

This is how we can create dynamic Datatable in Lightning Web Components.

I hope It'll help you somehow.

If you have any question Ask Me

Thanks for reading :)

Write a comment for suggestions and hit the heart icon.


11066
2

Tags: #lwc

Comments

  • Deevanshu pundir Avatar
    Deevanshu pundir - 1 year ago
    Nice block past

    Asif Ali Avatar
    Asif Ali - 1 year ago
    Haha, Thanks

Your message is required.

Get notified of new posts