We can call Apex in 2 different types in LWC.
- Imperative Call
- Wire service
Imperative call : Use when you want more control, such as calling the method on a button click or with dynamic parameters.
Wire Service : Use when you want declarative data binding and automatic caching.
In Lightning Web Components (LWC), you can call an Apex class to fetch or manipulate data in Salesforce. Here’s a step-by-step guide to calling an Apex method in LWC.
1. Create an Apex Class
The Apex method you want to call must be annotated with @AuraEnabled. Here’s an example:
public with sharing class ContactController {
@AuraEnabled
public static List getContacts() {
return [SELECT Id, Name, Email FROM Contact LIMIT 10];
}
}
2. Import Apex Method in LWC
In the JavaScript file of your LWC component, import the Apex method using the @salesforce/apex module.
import getContacts from '@salesforce/apex/ContactController.getContacts';
Example: Using Imperative Call
JavaScript (contactList.js)
import { LightningElement, track } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactList extends LightningElement {
@track contacts = [];
@track error;
// Method to call Apex
fetchContacts() {
getContacts()
.then((result) => {
this.contacts = result; // Assign result to contacts
this.error = undefined;
})
.catch((error) => {
this.error = error; // Capture the error
this.contacts = [];
});
}
}
Example: Using Wire Service
import { LightningElement, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactList extends LightningElement {
@wire(getContacts)
contacts; // Automatically fetches contacts
}
Imperative vs. Wire Service
| Feature | Imperative Call | Wire Service |
|---|---|---|
| When to Use | For dynamic actions (e.g., button click). | For automatic, declarative data binding. |
| Control | Full control over the invocation and timing. | Automatically fetches data and caches it. |
| Caching | No automatic caching. | Automatically caches data on the client side. |
| Parameters | Easily supports dynamic parameters. | Parameters need to be predefined. |
Best Practices
- Use Wire Service:
- For scenarios where data changes infrequently and needs to be displayed automatically.
- Use Imperative Call:
- For dynamic user-driven interactions or when handling complex logic.
- Error Handling:
- Always handle errors gracefully using
.catch()(for imperative) or check theerrorproperty (for wire service).
- Always handle errors gracefully using
- Governor Limits:
- Ensure your Apex method is optimized to avoid hitting Salesforce governor limits.
This approach ensures a clean and efficient way to fetch or manipulate data in your LWC components using Apex. Let me know if you need further clarification!

