Sub topic 2
Choosing fields and reading record data
Assume you know JavaScript modules, Lightning web component structure, and the @api recordId property supplied on a record page.
Choosing `fields` or `optionalFields`
The getRecord adapter reads only the fields you request. Put fields that the component must have in fields. Put fields that may be unavailable because of permissions or configuration in optionalFields.
A missing required field makes the wire return an error. An unavailable optional field is omitted from the returned data.
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue, getFieldDisplayValue } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
export default class AccountSummary extends LightningElement {
@api recordId;
@wire(getRecord, {
recordId: '$recordId',
fields: [NAME_FIELD],
optionalFields: [INDUSTRY_FIELD]
})
account;
get name() {
return getFieldValue(this.account.data, NAME_FIELD);
}
get industry() {
return getFieldDisplayValue(this.account.data, INDUSTRY_FIELD);
}
}Import field references from @salesforce/schema instead of writing API names as strings. These references help Salesforce validate dependencies and support metadata changes.
Working with `data` and `error`
A wired property receives an object with data and error states. The template should render values only when data exists and should provide a useful message when error exists.
<template>
<template lwc:if={account.data}>
<p>Name: {name}</p>
<p>Industry: {industry}</p>
</template>
<template lwc:if={account.error}>
<p>The record could not be loaded.</p>
</template>
</template>The wire service can provision new results when recordId changes or the Lightning Data Service cache updates.
Extracting field values
getFieldValue returns the stored value. getFieldDisplayValue returns the formatted value shown to users, such as a formatted date, currency, or picklist label. Both helpers accept the wire's data object and the imported field reference.
If an optional field was not returned, the helper returns undefined. Check for that case when the field is not guaranteed.
Exercise
Why is Industry in optionalFields instead of fields in the example?
Show answer
The component can still display the required Account Name if Industry is unavailable because of permissions or configuration.