Sub topic 3
What a wire gives you: the result object
This chapter assumes you can write a basic LWC with @wire, read an @AuraEnabled(cacheable=true) Apex method, and use promises and async/await. Before you can refresh wired data with refreshApex, you need to know exactly what the wire hands your component. This chapter covers that object, how its shape changes over time, and why later chapters pass it back to the platform unchanged.
The shape of a wire result
When you wire a cacheable Apex method, the wire service delivers the outcome of each request as a plain-looking object with two properties:
| Property | Holds | When it is set |
|---|---|---|
| `data` | The value the Apex method returned | After a successful response |
| `error` | The failure details | After a failed response |
Normally only one of the two is set. A success sets data and clears error. A failure sets error and clears data. Before the first response arrives, neither is set.
This shape is the same whether you bind the wire to a property or to a function. The binding only decides where the object ends up.
Binding to a property
The shortest form decorates a property. The wire service assigns the result object to that property each time a new response arrives.
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactListSimple extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
}After the first response, this.contacts is the whole result object. The value you want is this.contacts.data, not this.contacts. The template reads both parts through the property:
<template>
<template lwc:if={contacts.data}>
<template for:each={contacts.data} for:item="contact">
<p key={contact.Id}>{contact.Name}: {contact.Email}</p>
</template>
</template>
<template lwc:if={contacts.error}>
<p>Could not load contacts.</p>
</template>
</template>The property holds the object the platform created. You did not build it, and you should not replace it. That matters in the next chapter, because the property is exactly what you pass to refreshApex.
Binding to a function
If you need to run code when a response arrives, decorate a function instead. The wire service calls it with the same result object as its single argument.
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactList extends LightningElement {
@api recordId;
contacts;
error;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts(result) {
const { data, error } = result;
if (data) {
this.contacts = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.contacts = undefined;
}
}
}Here the component copies data and error into its own fields. Those fields are not the result object. They are just the values taken out of it. The result object itself is the result parameter, and it disappears when the function returns unless you save it. This component does not save it yet, so it could not call refreshApex. The next chapters fix that by also storing result in a field.
Property versus function
| Question | Property wire | Function wire |
|---|---|---|
| Where is the result object? | In the decorated property | In the function's parameter |
| Do you keep it automatically? | Yes | No, you must save it yourself |
| Where do you read the values? | `this.contacts.data` | Wherever you copied them |
| Best for | Simple display | Reshaping data, side effects, custom state |
The object changes over time
The wire does not mutate one object forever. Each new provisioning delivers a new result object. For a property wire, the platform assigns a fresh object to the property. For a function wire, it calls the function again with a fresh argument.
Three situations trigger a new delivery:
- The component connects and the first response arrives.
- A reactive parameter changes, such as
$recordIdgetting a new value. - The data is re-fetched, for example by
refreshApex.
Because a new object arrives each time, a reference you saved earlier can become out of date. For this reason, a function wire that stores the result should overwrite its field on every call, not just the first. The spine's function example does this by assigning this.wiredContactsResult = result at the top of the handler, before any branching.
Handle the "nothing yet" state
A function wire can be called when neither data nor error has a value. Write the handler so that case does nothing harmful. The if (data) ... else if (error) shape does this, because it skips both branches.
There is one trap in that shape. if (data) tests truthiness. An Apex method that returns a list always gives you an array, and an empty array is truthy, so lists are safe. A method that returns a number, a string, or a boolean could return 0, '', or false, and the test would treat a valid answer as missing. For scalar return types, test data !== undefined instead.
Wire data is read-only
The value in data is read-only. The platform shares the same cached data between components, so it protects it from changes. If you try to change a field on a record in data, or push onto the array, the assignment fails. Depending on the context it throws an error or silently has no effect.
To edit, make a copy and edit the copy:
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactEditor extends LightningElement {
@api recordId;
draftContacts = [];
error;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts({ data, error }) {
if (data) {
this.draftContacts = data.map((contact) => ({ ...contact }));
this.error = undefined;
} else if (error) {
this.error = error;
this.draftContacts = [];
}
}
}data.map((contact) => ({ ...contact })) builds a new array of new objects, so draftContacts is yours to change. The spread copies one level, which is enough for flat records like Contact. If a record includes nested objects, such as a child relationship result, copy the nested level too.
Notice what this component did with the parameter. It destructured { data, error } right in the signature, so it never holds the result object. That is fine for display and editing. It also means this component has no way to call refreshApex. Keeping the object is a deliberate choice you make when you need a refresh.
Why the whole object matters
A natural question: why does the object matter, when data already holds the records? The reason is what comes next. refreshApex does not take a method name or a list of records. It takes the result object that the wire provisioned, and uses it to find which wire to re-run. The documented rule is to pass the original object, so treat these as three different things:
- The result object: what the wire provisioned. Pass this to
refreshApex. result.dataandresult.error: parts of it. Do not pass these.- Your own copy of the values, or a new object with the same properties: it looks identical but is not what the wire provisioned. Do not pass it.
The platform does not document how it links the object to the wire, so do not depend on any internal detail. Rely on the rule: keep the object the wire gave you, and pass that same object back.
Reading errors
The error value is the failure object from the Apex call or the network. For Apex errors, a message commonly appears in error.body.message, and in some cases body is an array. Avoid writing code that assumes one exact shape. A defensive helper keeps this in one place:
export function reduceError(error) {
if (!error) {
return 'Unknown error';
}
if (Array.isArray(error.body)) {
return error.body.map((e) => e.message).join(', ');
}
if (error.body && typeof error.body.message === 'string') {
return error.body.message;
}
return error.message || 'Unknown error';
}Using it in a function wire is one line: this.errorMessage = reduceError(error). Handling errors during a save and a refresh is covered in a later chapter. For now, remember that error is part of the same result object and is cleared when a later request succeeds.
Common mistakes at this stage
- Reading
this.contactsas if it were the array. With a property wire it is the result object, so usethis.contacts.data. - Expecting a function wire to remember its argument. It does not. Save the object yourself.
- Mutating
datadirectly. Copy it first. - Testing
if (data)for a method that can return0,'', orfalse. - Destructuring the parameter and then wanting the object later. Once you destructure in the signature, you cannot get the object back.
Exercise
A component uses @wire(getContacts, { accountId: '$recordId' }) wiredContacts({ data, error }) { ... } and copies data into this.contacts. A developer later wants to call refreshApex after a save. Why is the current code not enough, and what is the smallest change that keeps the object available?
Show answer
The signature destructures the parameter, so the result object is never stored and only its parts reach the component. Change the signature to accept the whole object, for example wiredContacts(result), save it in a field such as this.wiredContactsResult = result on every call, and then destructure data and error from result inside the function. The field is what you later pass to refreshApex.
Exercise
A property wire is declared as @wire(getContacts, { accountId: '$recordId' }) contacts;. A handler runs this.contacts.data.push(newContact) and nothing changes on screen. Give the reason and a correct approach.
Show answer
The data array is read-only wire data, so it cannot be modified in place. Copy it into your own field, for example this.draft = [...this.contacts.data, newContact], and render from the copy, or save the change on the server and refresh the wire.