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());
}