Sub topic 8
Saving a change, then refreshing
This chapter combines a non-cacheable Apex method with refreshApex. It assumes you can wire a cacheable Apex method, read the wired result object, and use async/await. Earlier chapters covered why cached data goes stale and what to pass to refreshApex.
The problem to solve
A wired, cacheable method returns data from the client-side cache when it can. If a user edits a contact, the cached list still shows the old email. The list will not update until something tells the wire to fetch again.
Cacheable methods cannot change data, so the edit has to go through a second Apex method. That method is not cacheable, and you call it imperatively. After it succeeds, you call refreshApex so the wire fetches fresh data.
The two Apex methods
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
];
}
@AuraEnabled
public static void updateEmail(Id contactId, String email) {
Contact c = new Contact(Id = contactId, Email = email);
update as user c;
}
}getContacts is marked cacheable=true, so a component can wire it. updateEmail has no cacheable setting, so it can run DML. update as user enforces the running user's object and field permissions.
The sequence
The order matters. The refresh must run after the save finishes. If it runs earlier, the server returns the old data and the list does not change.
Version with a property wire
When the wire is bound to a property, that property holds the result object. Pass the property to refreshApex.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class ContactListSimple extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
async handleSave(event) {
const { contactId, email } = event.detail;
await updateEmail({ contactId, email });
await refreshApex(this.contacts);
}
}Two await statements run in order. The first waits for the DML to finish. The second waits for the new data to arrive. If updateEmail rejects, execution jumps out of handleSave and the refresh never runs.
Version with a function wire
A function wire receives the result object as an argument. Store it, then pass the stored object later.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class ContactList extends LightningElement {
@api recordId;
contacts;
error;
wiredContactsResult;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts(result) {
this.wiredContactsResult = result;
const { data, error } = result;
if (data) {
this.contacts = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.contacts = undefined;
}
}
async handleSave(event) {
const { contactId, email } = event.detail;
try {
await updateEmail({ contactId, email });
await refreshApex(this.wiredContactsResult);
} catch (e) {
this.error = e;
}
}
}The line this.wiredContactsResult = result; runs on every provisioning, before the data is unpacked. Keep the whole object. Pulling out data and passing only that gives refreshApex nothing to work with.
What the template sees
With the property version, the template reads contacts.data and contacts.error. When refreshApex provisions a new value, the template re-renders.
<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>Quick comparison
| Wire style | What you keep | What you pass |
|---|---|---|
| Property | The decorated property | `this.contacts` |
| Function | The `result` argument, saved in a field | `this.wiredContactsResult` |
Exercise
In handleSave, a developer calls refreshApex(this.contacts) before awaiting updateEmail, so both calls run at nearly the same time. The list sometimes still shows the old email. Why, and how do you fix it?
Show answer
The refresh can reach the server before the update has committed, so it returns the old data. Await updateEmail first, then call refreshApex: await updateEmail({ contactId, email }); await refreshApex(this.contacts);
Exercise
Why can't updateEmail be marked cacheable=true so it can be wired?
Show answer
Cacheable methods cannot modify data, so Apex does not allow DML in them. The update must be a non-cacheable method called imperatively.