Sub topic 6
Calling Apex declaratively with @wire
This chapter assumes you can write basic Apex (classes, SOQL, DML) and basic Lightning web components (templates, JavaScript classes, decorators). It also assumes you know that an @AuraEnabled(cacheable=true) method is a read-only Apex method the client can cache.
What @wire does
@wire is a decorator that connects a component property or function to an Apex method. The Lightning runtime calls the method for you. It calls it when the component is connected to the page, and it calls it again when a reactive parameter changes. You don't write the call yourself.
The Apex method must be @AuraEnabled(cacheable=true). A wired method can't perform DML. The platform enforces this, so a non-cacheable method fails when you try to wire it.
Wiring to a property
Start with the Apex method.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}Then import it and wire it in the component.
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 import path has the form @salesforce/apex/ClassName.methodName. The @wire decorator takes the imported method and a configuration object. The keys of that object match the Apex parameter names.
The $ prefix in '$recordId' marks the parameter as reactive. The value is the name of a property on the component, written as a string. When recordId changes, the runtime calls the method again with the new value.
The result shape
When you wire to a property, the property holds an object with two fields: data and error. Both are undefined until the first response arrives.
<template>
<template lwc:if={contacts.data}>
<ul>
<template for:each={contacts.data} for:item="c">
<li key={c.Id}>{c.Name}</li>
</template>
</ul>
</template>
<template lwc:if={contacts.error}>
<p>Could not load contacts.</p>
</template>
</template>Only one of data and error is set at a time. Check each one before you use it.
Wiring to a function
Wire to a function when you need to process the result or handle errors in code. The runtime passes the function one object with data and error.
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactNames extends LightningElement {
@api recordId;
names = [];
errorMessage;
@wire(getContacts, { accountId: '$recordId' })
handleContacts({ data, error }) {
if (data) {
this.names = data.map((c) => c.Name);
this.errorMessage = undefined;
} else if (error) {
this.errorMessage = error.body ? error.body.message : error.message;
this.names = [];
}
}
}The function runs each time new data or an error arrives. Reset the other value in each branch so stale data isn't shown next to a new error.
How the call flows
Common errors
- Wiring a non-cacheable method. Add
cacheable=true, or call the method imperatively if it must change data. - Forgetting the
$. Without it, the string'recordId'is sent to Apex as a literal value. - Reading
contactsas an array. The property is{ data, error }. Usecontacts.data. - Using the value too early. Parameters that are
undefinedcan leave the wire waiting. The method isn't called until all reactive parameters have values. - Expecting fresh data after an edit. Cacheable results can come from the client cache. The next chapter covers
refreshApex.
Exercise
Exercise
A component wires getContacts with { accountId: 'recordId' } (no $). What does Apex receive for accountId, and how do you fix it?
Show answer
Apex receives the literal string "recordId", not the record's ID, so the call fails or returns nothing useful. Write '$recordId' so the runtime reads the component's recordId property and re-runs the call when it changes.
Exercise
You need to call a method that inserts a Contact when the user clicks Save. Can you use @wire? Why or why not?
Show answer
No. Wired methods must be cacheable=true, and cacheable methods can't perform DML. Call the method imperatively instead.