Sub topic 2
Passing data and a key-field
This chapter covers the two attributes every lightning-datatable needs before it can show a row: data and key-field. It assumes you can write a basic Lightning Web Component, wire an Apex method to it, and read JavaScript arrays, objects, and destructuring. Column definitions get their own chapter. Here the columns are only a placeholder, so the focus stays on the rows.
What the table expects
lightning-datatable takes three main inputs:
| Attribute | Type | Purpose |
|---|---|---|
| `data` | Array of objects | One object per row. |
| `columns` | Array of objects | Describes which property of each row object appears in which column. |
| `key-field` | String | The name of the property that uniquely identifies each row. |
The table does not know about Salesforce objects, fields, or SOQL. It sees a plain array of JavaScript objects. A Contact returned from Apex is just an object with properties such as Id, Name, and Email. Each column definition's fieldName is matched against those property names.
A minimal working example
Start with an Apex method that returns the rows. It is cacheable so the component can wire to it, and it selects Id because the table will use it as its key.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts() {
return [
SELECT Id, Name, Email, Phone, Birthdate
FROM Contact
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}The component wires the method and stores the result in data. The columns array is shown briefly here and explained in the next chapter.
import { LightningElement, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text', sortable: true },
{ label: 'Email', fieldName: 'Email', type: 'email' },
{ label: 'Phone', fieldName: 'Phone', type: 'phone' },
{ label: 'Birthdate', fieldName: 'Birthdate', type: 'date-local' }
];
export default class ContactTable extends LightningElement {
columns = COLUMNS;
data = [];
error;
wiredResult;
@wire(getContacts)
wiredContacts(result) {
this.wiredResult = result;
const { data, error } = result;
if (data) {
this.data = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.data = [];
}
}
}The template binds both arrays and names Id as the key.
<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
hide-checkbox-column>
</lightning-datatable>
</lightning-card>
</template>Three details in this wiring matter later:
datastarts as an empty array, notundefined. The table renders its empty state while it waits, and the template never passesundefinedto it.- The wired function is a function, not a property. It receives the whole result object, which lets the component keep
wiredResultfor a laterrefreshApexcall. hide-checkbox-columnremoves the selection checkboxes. Without it, the table shows a checkbox on every row and a select-all checkbox in the header. Row selection is covered in a later chapter.
What key-field does
key-field is the name of a property that exists on every row object. Its value must be unique across the rows in data. The table uses it for several jobs:
- Row identity. When you replace
data, the table matches the new rows to the old ones by key. This lets it keep row state, such as selection, stable. - Selection. The selected-rows list, and the
selected-rowsattribute you can use to preselect rows, are expressed as arrays of key values. - Events. Events such as
rowactionandrowselectionreport row objects that include your key property, so you can tell which record was touched. - Inline edits. Each draft value contains the changed fields plus the key-field value. This is how you know which record a draft belongs to. A later chapter relies on this.
The value should be a string. Id is the usual choice for records because Salesforce guarantees it is unique. If your rows are not records, such as aggregate query results or data from an external API, choose any property that is unique, or add one when you build the array.
If you forget key-field or name a property that rows do not have, rows will not behave correctly. Typical symptoms are rows that do not render, a console error, or selection that acts on the wrong rows. When rows look wrong, check the key first.
Matching property names to field names
Each column's fieldName is looked up as a property on the row object. A mismatch gives an empty column, not an error. Two common causes:
- The Apex query did not select the field. Apex returns only the fields in the
SELECTlist. A column forPhoneis blank ifPhoneis not selected. - The value is nested. A query such as
SELECT Id, Name, Account.Name FROM ContactreturnsAccountas a nested object. A column withfieldName: 'Account.Name'does not resolve it, because the datatable reads top-level properties only.
The fix for nested values is to flatten each row into a new object before you assign data. This version of the wired function adds an AccountName property. It assumes the Apex query also selects Account.Name and the column definition uses fieldName: 'AccountName'.
@wire(getContacts)
wiredContacts(result) {
this.wiredResult = result;
const { data, error } = result;
if (data) {
this.data = data.map((contact) => ({
...contact,
AccountName: contact.Account?.Name
}));
this.error = undefined;
} else if (error) {
this.error = error;
this.data = [];
}
}The spread (...contact) keeps Id and every other property, so the key-field still works. The flattened array also leaves the original wired object untouched, which matters for the next section.
Data from a wire is read-only
Values from a wire adapter are read-only. Calling data.sort(...) or assigning data[0].Name = 'X' on the wired array fails or does nothing useful. Always copy before you change anything:
// Wrong: mutates the read-only wired array
this.data.sort(compareByName);
// Right: sorts a copy and assigns it
this.data = [...this.data].sort(compareByName);The copy has a second benefit. The table re-renders when you assign a new array to the property bound to data. Changing an element inside an existing array does not reliably trigger a refresh. The rule is to build a new array and assign it.
If you transform rows with map, as in the flattening example, copy each row too ({ ...contact }). Rows that you modify in place are still read-only objects.
Empty and error states
The table shows no rows when data is an empty array. It does not show a message unless you add one. Because data starts as [], the screen is blank both while loading and when the query returns nothing. Add your own messages in the template if the difference matters.
<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<template lwc:if={error}>
<p class="slds-p-around_small slds-text-color_error">
Could not load contacts.
</p>
</template>
<template lwc:else>
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
hide-checkbox-column>
</lightning-datatable>
</template>
</lightning-card>
</template>The wired function already sets error and clears data when the call fails, so the template can branch on error. Table-level and row-level error display, which uses the table's own error attributes, is a separate topic covered in a later chapter.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Table is blank, no error | `data` is `undefined`, an object instead of an array, or the query returned nothing | Initialize `data = []`, and check that the wired value is an array |
| One column is empty | `fieldName` does not match a property, or the field was not in the `SELECT` | Compare `fieldName` with the property names in the row objects |
| Related-object column is empty | Dot notation in `fieldName` | Flatten the row into a top-level property |
| Selecting one row selects another | Duplicate key values | Use a unique property as the key-field |
| "Cannot assign to read only property" | Mutating wired data | Copy the array and its rows first |
| Table does not update after a change | Array changed in place | Assign a new array to the bound property |
Exercise
A component queries aggregate results with SELECT StageName, COUNT(Id) total FROM Opportunity GROUP BY StageName. Each result row has StageName and total, but no Id. What should you use as the key-field, and how do you make it available to the table?
Show answer
Use a property that is unique across the rows. Each StageName appears once because of the GROUP BY, so it works as the key. Set key-field="StageName", or map the rows to add an explicit unique property such as rowKey. Note that Apex returns aggregate results as AggregateResult objects, so the Apex method should convert them into a wrapper class or map with plain properties before the component receives them. Never leave the key-field unset or point it at a property that does not exist on the rows.