Sub topic 2
Wiring to a Property and Rendering Data and Error
Assume you know JavaScript modules, LWC class structure, basic Apex, SOQL, and the @api decorator. A wired property receives an object with two possible fields: data for a successful result and error for a failed result.
Wiring to a Property
First, import the Apex method. The method must be public or global, static, and annotated with @AuraEnabled(cacheable=true).
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactList extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
}The template reads contacts.data and contacts.error:
<template>
<template lwc:if={contacts.data}>
<ul>
<template for:each={contacts.data} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>
<template lwc:elseif={contacts.error}>
<p>Could not load contacts.</p>
</template>
</template>The wire service provisions a new value when the component loads or when a reactive parameter changes.
Reactive Parameters with `$`
The $ prefix makes recordId reactive. When Salesforce changes recordId, the wire service calls getContacts again with the new value.
Without $, the string "recordId" would be passed as the account ID. Use $recordId when a parameter should come from a component property.
Wiring to a Function
Wire to a function when you need to transform results, clear old values, or extract an error message:
@wire(getContacts, { accountId: '$recordId' })
wiredContacts({ data, error }) {
if (data) {
this.rows = data;
this.errorMessage = undefined;
} else if (error) {
this.rows = undefined;
this.errorMessage = error.body?.message ?? error.message;
}
}The template can then render rows and errorMessage. Keep the success and failure paths separate so stale data does not remain visible after an error.
Exercise
What does $recordId do in the wire configuration?
Show answer
It makes the Apex parameter reactive, so the wire service runs again when recordId changes.