2

I am really having a weird issue where I am trying to simply render a couple of records on a LWC table. I am getting all the wired data right and I believe all is setup correct. Don't know what I am missing.

The data wont show on the screen. Products

import { LightningElement,wire } from 'lwc';
import relatedProducts from '@salesforce/apex/OpportunityRelatedProducts.getOpportunityProducts';
const COLS = [
    {
        label: 'Name',
        fieldName: 'Name',
        type: 'text'
    }, {
        label: 'Price Book',
        fieldName: 'PricebookEntryId',
        type: 'text'
    }, {
        label: 'Quantity',
        fieldName: 'Quantity',
        type: 'number'
    }, {
        label: 'Unit Price',
        fieldName: 'UnitPrice',
        type: 'number'
    }
];
export default class LineItemTable extends LightningElement {
    results=[];
    columns = COLS;
    @wire(relatedProducts) lineitems({error,data}){
        if(data){
            console.log('****Data is: '+data);
            data.forEach(record => {
                this.results.push(record);
            });
            console.table(this.results);
        }
        else if(error){
            console.log('****There was an error');
        }
    }

    renderedCallback(){
        console.log('****Inside rendered');
    }

}
    <template>
    <template if:true={results}>
    <div>
        <lightning-datatable columns={columns} data={results} key-field="Id"></lightning-datatable>
    </div>
    </template>
   
</template>
    public with sharing class OpportunityRelatedProducts {

    @AuraEnabled(Cacheable = true)
    public static list<OpportunityLineItem> getOpportunityProducts() {
        try {
            return [select Id,Name, PricebookEntryId,Quantity,UnitPrice from opportunitylineitem where opportunityid = '0067d00000HIQBeAAP' ];
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}

1 Answer 1

3

In LWC datatable push method does not have any reactive effect.

So try this:

if(data){
        console.log('****Data is: '+data);
        const lstData = [];
        data.forEach(record => {
            lstData.push(record);
        });
        this.results = lstData;
}
3
  • Perfect! "In LWC datatable push method does not have any reactive effect." Will remember this. Jan 10, 2021 at 11:47
  • 1
    @MassReaper Super-inefficient code warning. Simply do: this.results = [...data]; for a quick copy operation. Also, @track will make push, etc, reactive.
    – sfdcfox
    Jan 11, 2021 at 10:59
  • Actually correct about efficiency, but @sfdcfox in LWC datatable even making @track does not make it reactive. Until we assign the data again using ... or using above logic. Jan 11, 2021 at 12:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .