Sub topic 4
Wiring to a property and rendering data and error
This chapter assumes you can write a basic Lightning Web Component and have an Apex method with @AuraEnabled(cacheable=true) already imported into your JavaScript file, as covered in the earlier chapters. You should also be comfortable with @api properties and template conditionals. Here you will wire that imported method to a property and render what the wire gives back.
What a wired property holds
When you put @wire on a class field, the framework owns that field. You do not assign to it. The wire service assigns it for you, and it assigns the same kind of value every time: an object with two keys, data and error.
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;
}After this decorator runs, this.contacts is an object shaped like one of these:
| Moment | `contacts.data` | `contacts.error` |
|---|---|---|
| Before the first response arrives | `undefined` | `undefined` |
| Apex returned successfully | the return value of the method | `undefined` |
| Apex threw an exception, or the call failed | `undefined` | an error object |
Only one of the two keys is set at a time. The framework replaces the whole contacts object on each new result, so the template and any getters that read contacts.data re-evaluate automatically.
The first row matters most for new developers. The property exists immediately, but its keys are empty until the server responds. Any code that reads this.contacts.data too early sees undefined, not an empty list.
The life of a wired value
The wire is not a one-time call. It provisions a value, and it provisions a new one whenever the reactive inputs change (the next chapter covers the $ prefix in detail).
Your template needs to handle all three states. If it only handles HasData, users see a blank area while loading and no explanation when something fails.
Rendering data and error in the template
The template below handles the success and failure states with lwc:if and lwc:elseif.
<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>Three details in this markup are worth understanding.
- Dot access on a wired property is allowed in templates. LWC templates permit simple property paths such as
contacts.data. They do not permit expressions such ascontacts.data.length > 0. Anything computed belongs in a getter in the JavaScript class. - Every iterated element needs a
key. The key must be unique among siblings and stable.contact.Idfits because the SOQL query selectsId. If you leaveIdout of the query,key={contact.Id}evaluates toundefinedand rendering breaks. - The error branch is not evaluated until data is falsy. Because only one of the two keys is set, the order of the branches rarely matters for correctness. It does matter for readability, so put the success path first.
Adding a loading branch
The template above shows nothing while the request is in flight. Add an lwc:else branch to cover that state.
<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 lwc:else>
<p>Loading contacts...</p>
</template>
</template>lwc:else runs when neither data nor error is truthy. That is exactly the loading state in the diagram above.
The empty list trap
An empty array is truthy in JavaScript. If the account has no contacts, Apex returns [], contacts.data is truthy, and the lwc:if branch renders an empty <ul>. The user sees nothing and cannot tell whether the component broke.
To show a message for an empty result, compute it in a getter and branch on that.
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactListWithEmpty extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
get hasContacts() {
return Boolean(this.contacts.data && this.contacts.data.length > 0);
}
get isEmpty() {
return Boolean(this.contacts.data && this.contacts.data.length === 0);
}
get errorMessage() {
const error = this.contacts.error;
if (!error) {
return undefined;
}
return error.body ? error.body.message : error.message;
}
}<template>
<template lwc:if={hasContacts}>
<ul>
<template for:each={contacts.data} for:item="contact">
<li key={contact.Id}>{contact.Name} ({contact.Email})</li>
</template>
</ul>
</template>
<template lwc:elseif={isEmpty}>
<p>This account has no contacts.</p>
</template>
<template lwc:elseif={contacts.error}>
<p>Could not load contacts: {errorMessage}</p>
</template>
<template lwc:else>
<p>Loading contacts...</p>
</template>
</template>The getters read this.contacts on each render, so they update when the wire provisions a new value. The Boolean(...) wrapper keeps the getters returning true or false and not undefined.
Reading the error
The error value is not always the same shape. For an exception thrown from Apex (for example an AuraHandledException, or a query failure surfaced by the platform), the message sits at error.body.message. For a network or framework failure there may be no body, and the message is at error.message. The expression error.body ? error.body.message : error.message handles both.
The next chapters cover error handling in more depth, including a helper that flattens several error shapes into a list of strings. For a property wire, the getter above is enough.
Wired data is read-only
The object the wire provisions is read-only. You can read it, loop over it, and pass it to child components. You cannot change it in place. This is a common source of confusing runtime errors.
This code fails:
get sortedContacts() {
// Throws: the provisioned array cannot be modified.
return this.contacts.data.sort((a, b) => a.Name.localeCompare(b.Name));
}Array.prototype.sort changes the array it is called on, which is not allowed here. Copy first, then sort the copy:
get sortedContacts() {
if (!this.contacts.data) {
return [];
}
return [...this.contacts.data].sort((a, b) =>
a.Name.localeCompare(b.Name)
);
}The same rule applies to adding fields to a record, such as contact.displayName = .... Build new objects with spread syntax instead:
get displayRows() {
return (this.contacts.data || []).map((contact) => ({
...contact,
label: `${contact.Name} <${contact.Email}>`
}));
}Assigning to this.contacts yourself is also wrong. The decorator owns the field, and your assignment will be overwritten on the next provision or may not behave as expected. If you need to store a transformed copy of the result, use a separate field. That is the main reason to wire to a function, which the next chapter explains.
Where and when you can read the wired value
Because data and error are empty until the response arrives, lifecycle hooks are a poor place to read them.
- In
constructorandconnectedCallback, the wire has usually not provisioned anything yet.this.contacts.dataisundefined. - In
renderedCallback, a value may or may not be present, and the hook runs again after every render. - In getters used by the template, the read happens on each render, so the value is correct whenever it changes. This is the safest pattern.
If you need to run logic when data arrives, such as sending an event or setting up a related field, a property wire is the wrong tool. Wire to a function instead.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Blank component, no error in the console | Template handles only `data`, and the call failed | Add an `lwc:elseif` branch for `error` |
| Empty list with no message | `[]` is truthy, so the data branch rendered | Use a getter such as `isEmpty` |
| "Cannot assign to read only property" | Mutating the provisioned array or its records | Copy with spread, then change the copy |
| `[object Object]` on screen | Binding `contacts.error` directly | Extract `error.body.message` in a getter |
| Rendering fails with a key warning | `Id` missing from the SOQL `SELECT` list | Add `Id` to the query |
| `undefined` in `connectedCallback` | Reading the wire before it has provisioned | Read in a getter or wire to a function |
Exercise
A component wires contacts to an Apex method and uses lwc:if={contacts.data} to render a list. For an account with no contacts, the page shows an empty area with no message and no error. Why does this happen, and how do you fix it?
Show answer
Apex returns an empty list []. An empty array is truthy in JavaScript, so contacts.data is truthy and the data branch renders an empty <ul>. Add a getter such as get isEmpty() { return Boolean(this.contacts.data && this.contacts.data.length === 0); } and use lwc:elseif={isEmpty} to show a "no contacts" message. Check hasContacts (length greater than zero) before it in the same chain.
Exercise
You add get sortedContacts() { return this.contacts.data.sort(...); } and the component throws as soon as data arrives. What is wrong, and what is the corrected getter?
Show answer
The wire provisions read-only data, and sort changes the array in place. Copy the array first: get sortedContacts() { return this.contacts.data ? [...this.contacts.data].sort((a, b) => a.Name.localeCompare(b.Name)) : []; }.