Calling Apex from LWC · Lesson 17 of 25
Call Apex from LWC with @wire
Lightning Data Service handles single records well, but real components need lists, filters, joins and aggregates: "open opportunities for this account over $50,000", "top 10 products this quarter". For those you write an Apex method and call it from your component. When the call only reads data, the cleanest way is to wire it, just like getRecord.
In this lesson
- Writing an Apex method for LWC
- Wiring it with reactive parameters
- Data, error and empty states
- Refreshing with refreshApex
The Apex class
// OpportunityController.cls
public with sharing class OpportunityController {
@AuraEnabled(cacheable=true)
public static List<Opportunity> getOpenOpportunities(Id accountId, Decimal minAmount) {
return [
SELECT Id, Name, StageName, Amount, CloseDate
FROM Opportunity
WHERE AccountId = :accountId AND IsClosed = false AND Amount >= :minAmount
WITH USER_MODE
ORDER BY CloseDate ASC
LIMIT 50
];
}
}
@AuraEnabledmakes the method callable from Lightning components;cacheable=truemarks it read-only and lets the client cache the result. It's required for@wire.with sharingapplies the user's record access, andWITH USER_MODEalso enforces object and field permissions – always use both for UI-facing queries.- Bind variables (
:accountId) prevent SOQL injection. Add aLIMIT: a component should never load thousands of rows.
Wiring it
<!-- openDeals.html -->
<template>
<lightning-card title={title}>
<lightning-combobox label="Minimum amount" value={minAmountKey} options={amountOptions} onchange={handleMinChange}></lightning-combobox>
<template lwc:if={deals.data}>
<template lwc:if={hasDeals}>
<ul>
<template for:each={deals.data} for:item="deal">
<li key={deal.Id}>{deal.Name} – {deal.StageName} – ${deal.Amount}</li>
</template>
</ul>
</template>
<template lwc:else><p>No open deals above this amount.</p></template>
</template>
<template lwc:elseif={deals.error}>
<p class="slds-text-color_error">{errorMessage}</p>
</template>
</lightning-card>
</template>
// openDeals.js
import { LightningElement, api, wire } from 'lwc';
import getOpenOpportunities from '@salesforce/apex/OpportunityController.getOpenOpportunities';
export default class OpenDeals extends LightningElement {
@api recordId; // the Account page we're on
minAmountKey = '0';
amountOptions = [
{ label: 'Any amount', value: '0' },
{ label: '$50,000+', value: '50000' },
];
// parameter names must match the Apex method's parameter names
@wire(getOpenOpportunities, { accountId: '$recordId', minAmount: '$minAmount' })
deals;
get minAmount() {
return Number(this.minAmountKey);
}
get hasDeals() {
return this.deals.data.length > 0;
}
get title() {
return this.deals.data ? `Open deals (${this.deals.data.length})` : 'Open deals';
}
get errorMessage() {
return this.deals.error?.body?.message ?? 'Unknown error';
}
handleMinChange(event) {
this.minAmountKey = event.detail.value; // changes $minAmount → the wire calls Apex again
}
}
▌Open deals (2)
Minimum amount [Any amount ▾]
• Acme renewal – Negotiation – $120000
• Acme add-on – Proposal – $18000
› choose “$50,000+” in Minimum amount
▌Open deals (2)
Minimum amount [$50,000+ ▾]
• Acme renewal – Negotiation – $120000
• Acme add-on – Proposal – $18000
› new data from getOpenOpportunities
▌Open deals (1)
Minimum amount [$50,000+ ▾]
• Acme renewal – Negotiation – $120000
getOpenOpportunities wired with {"accountId":"001XX000003DGb2","minAmount":50000}- Import an Apex method as
@salesforce/apex/ClassName.methodName. - The configuration object maps Apex parameter names to values. A
'$property'value is reactive: whenminAmountchanged, the wire asked Apex again with the new value – the panel's last line shows the wire's current parameters,minAmount: 50000, and the list updated with the new result. - If a reactive parameter is
undefined, the wire waits and doesn't call Apex – useful when the record Id isn't known yet. - Wired data is read-only; copy it before changing it.
When Apex throws
// openDeals.js – same component
▌Open deals Minimum amount [Any amount ▾] You do not have access to the Opportunity object.
An exception in Apex (or a permission error from WITH USER_MODE) arrives as deals.error. For messages meant for users, throw an AuraHandledException in Apex – its message is passed to the client cleanly.
refreshApex
Because cacheable results are cached on the client, a wired list doesn't change by itself after you edit data. Keep the wired result and refresh it after a save:
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getOpenOpportunities from '@salesforce/apex/OpportunityController.getOpenOpportunities';
export default class OpenDeals extends LightningElement {
@api recordId;
wiredDeals; // keep the whole provisioned value
@wire(getOpenOpportunities, { accountId: '$recordId', minAmount: 0 })
handleDeals(result) {
this.wiredDeals = result; // { data, error }
if (result.data) {
this.rows = result.data.map((d) => ({ ...d, isBig: d.Amount > 100000 }));
}
}
async handleSaved() {
await refreshApex(this.wiredDeals); // re-runs the Apex call and updates the cache
}
}
@wire Apex checklist
@AuraEnabled(cacheable=true),with sharing,WITH USER_MODE, bind variables and aLIMIT.- Parameter names in JavaScript match the Apex signature exactly.
- Reactive
'$'parameters re-run the query; pass the whole wired value torefreshApex. - Cacheable methods can't do DML – for saves, call Apex imperatively (next lesson).
Practice
Try it yourself
Wire
ContactController.getContacts(accountId)and show the contacts' names, or "No contacts" for an empty list.Show solution
// ContactController.cls public with sharing class ContactController { @AuraEnabled(cacheable=true) public static List<Contact> getContacts(Id accountId) { return [SELECT Id, Name FROM Contact WHERE AccountId = :accountId WITH USER_MODE ORDER BY Name LIMIT 100]; } }<!-- accountContacts.html --> <template> <template lwc:if={hasContacts}> <template for:each={contacts.data} for:item="c"> <p key={c.Id}>{c.Name}</p> </template> </template> <template lwc:else><p>No contacts</p></template> </template>// accountContacts.js import { LightningElement, api, wire } from 'lwc'; import getContacts from '@salesforce/apex/ContactController.getContacts'; export default class AccountContacts extends LightningElement { @api recordId; @wire(getContacts, { accountId: '$recordId' }) contacts; get hasContacts() { return this.contacts.data?.length > 0; } }Asha Verma Ravi Kumar
Quick check
What annotation does an Apex method need for @wire?
@AuraEnabled(cacheable=true).
What happens when a '$' parameter changes?
The wire calls the Apex method again with the new value.
What do you pass to refreshApex?
The entire value the wire provisioned (the result object), not just its data.
Summary
- Expose read-only, secure Apex with @AuraEnabled(cacheable=true), with sharing and WITH USER_MODE.
- @wire it with reactive '$' parameters; render data, error and empty states.
- Refresh cached results with refreshApex after changes.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.