March 26, 2020

How to iterate over Records returned By Wire Service in LWC

Sample Code:

HTML:

<template>

    <div> 

        <lightning-datatable key-field="Id"
                             data={accountsWithIndustry}
                             columns={columns}
                             hide-checkbox-column="true" 
                             show-row-number-column="true">
        </lightning-datatable>

    </div>    
    <div> 

        <lightning-datatable key-field="Id"
                             data={accountsWithoutIndustry}
                             columns={columns}
                             hide-checkbox-column="true" 
                             show-row-number-column="true">
        </lightning-datatable>

    </div>       
   
</template>


JavaScript:

import { LightningElement, wire, track } from 'lwc';
import fetchAccounts from '@salesforce/apex/ExampleController.fetchAccounts';

const columns = [ 
    { label: 'Name', fieldName: 'Name' }, 
    { label: 'Industry', fieldName: 'Industry' }, 
];

export default class Example extends LightningElement {

    @track accountsWithIndustry;
    @track accountsWithoutIndustry;
    @track columns = columns;

    @wire(fetchAccounts)
    accountData({ error, data }) {

        if ( data ) {
           
            var tempAccountsWithIndustry = [];
            var tempAccountsWithoutIndustry = [];

            for ( var i = 0; i < data.length; i++ ) {

                if ( data[ i ].Industry )
                    tempAccountsWithIndustry.push( data[ i ] );
                else
                    tempAccountsWithoutIndustry.push( data[ i ] );

            }

            this.accountsWithoutIndustry = tempAccountsWithoutIndustry;
            this.accountsWithIndustry = tempAccountsWithIndustry;
            console.log( JSON.stringify( this.accountsWithIndustry ) );
            console.log( JSON.stringify( this.accountsWithoutIndustry ) );

        }
   
   
    }

}


JavaScript-meta.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__Tab</target>   
    </targets>
</LightningComponentBundle>


Apex Class:

public with sharing class ExampleController {

    @AuraEnabled(cacheable=true)
    public static List < Account > fetchAccounts() {

        return [ SELECT Id, Name, Industry FROM Account LIMIT 10 ];
       
    }
   
}


Output:


No comments:

Post a Comment