What is the purpose of refreshApex, and how do you use it with wired data adapters?
Answer
Basics: Wired Apex (cacheable=true) results are cached client-side for performance, so after you save something, the old list can still show. refreshApex tells the wire to get fresh data. It is imported from @salesforce/apex.
How it works:
- Wire to a property or function and keep the entire provisioned object (not just
.data). - After a mutation (imperative Apex DML,
updateRecord, flow), callrefreshApex(this.wiredResult). - It returns a Promise; await it if you need to sequence actions.
- The wire re-emits fresh
{data, error}and the template re-renders. - When wiring to a function, store the whole argument in a field:
this.wiredResult = result.
Advanced / deep dive: The argument must be the exact value the wire provisioned. Passing result.data does nothing. refreshApex only affects wired adapters of cacheable Apex; it does not affect results fetched imperatively, which are your own variables, so re-call the method instead. For Lightning Data Service adapters (getRecord) use notifyRecordUpdateAvailable or getRecordNotifyChange from lightning/uiRecordApi (the newer name replaced the older one in recent releases; verify in current release notes). LDS operations such as updateRecord refresh their own wires automatically, so you only need refreshApex when Apex changed the data. When multiple components wire the same Apex call with the same params they share one cache entry; one refreshApex call refreshes the data for all of them. Be careful with refresh loops where a handler triggers a refresh that triggers the handler. Cache refresh issues a server round trip, so avoid calling it per keystroke; debounce.