3

I am trying to display two lightning datatables on a page. For the first one, I want to display only first row from the data I receive. Use case Scenario is to get most recent event data. For the second table, I would like to display all data. When I get my data, I am adding first element to variable mostRecent and I could see it has value in console. Second table works fine but first one does not. I do not understand why it won't render anything for the first table. To show an example, I have created this code using LWC component Reference guide for Datatable.

  <template>
    <div style="height: 300px;">
        <template if:true={mostRecent}>
        <lightning-datatable
                key-field="id"
                data={mostRecent}
                columns={columns}>
        </lightning-datatable>
        </template>
        <template if:true={data}>
        <lightning-datatable
                key-field="id"
                data={data}
                columns={columns}>
        </lightning-datatable>
        </template>
    </div>    
</template>

basic.js

import { LightningElement, track } from 'lwc';
import fetchDataHelper from './fetchDataHelper';

const columns = [
    { label: 'Label', fieldName: 'name' },
    { label: 'Website', fieldName: 'website', type: 'url' },
    { label: 'Phone', fieldName: 'phone', type: 'phone' },
    { label: 'Balance', fieldName: 'amount', type: 'currency' },
    { label: 'CloseAt', fieldName: 'closeAt', type: 'date' },
];

export default class BasicDatatable extends LightningElement {
    data = [];
    @track mostRecent = [];
    columns = columns;

    // eslint-disable-next-line @lwc/lwc/no-async-await
    async connectedCallback() {
        const data = await fetchDataHelper({ amountOfRecords: 100 });
        this.data = data;
        this.mostRecent.push(data[0]);
    }
}

fetchDataHelper.js

const recordMetadata = {
    name: 'name',
    email: 'email',
    website: 'url',
    amount: 'currency',
    phone: 'phoneNumber',
    closeAt: 'dateInFuture',
};

export default function fetchDataHelper({ amountOfRecords }) {
    return fetch('https://data-faker.herokuapp.com/collection', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json; charset=utf-8',
        },
        body: JSON.stringify({
            amountOfRecords,
            recordMetadata,
        }),
    }).then((response) => response.json());
}

1 Answer 1

4

This feels like it might be a bug; track isn't detecting the change to the array. I'll ask around. In the meantime, you can fix this by using an explicit array constructor:

this.mostRecent = [data[0]];

Demo

Edit: From the comments, it appears this was never supported, and I just didn't realize that. Always create a fresh array using whatever appropriate method (Array.map, Array.flat, etc).

5
  • 3
    I have always found it to work like this. push() does not work for tracked variables. Pushing to a local variable and then setting the tracked variable does. let tracked = []; tracked.push(data[0]); this.trackedVar = tracked;
    – CyberJus
    Aug 4, 2021 at 0:30
  • @CyberJus Yeah, you're creating a new object, so the runtime picks up on the change of objects. I presumed Array.push would work with track, but I personally never use it, as I always copy a fresh array. Do you happen to know if this is documented anywhere before I go off making a Bug for it?
    – sfdcfox
    Aug 4, 2021 at 1:00
  • Not super clear based on this: lwc.dev/guide/javascript_reactive#reactive-data-types Says it observes changes but push does not qualify as an observed change. Interesting that after setting the this.trackedVar, this works as expected to change the value => this.trackedVar[0] = data[1];
    – CyberJus
    Aug 4, 2021 at 12:55
  • @CyberJus Right. In the example, they show how setHours doesn't affect the render, similar behavior with push, I suppose. I agree, it could be clarified better.
    – sfdcfox
    Aug 4, 2021 at 13:08
  • @sfdcfox I see what the issue was. thank you, your solution works!
    – jejejean
    Aug 4, 2021 at 14:57

You must log in to answer this question.

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