Introduction
In Salesforce Lightning Web Components (LWC), working with Apex methods to interact with the Salesforce server can be done in two primary ways:
- Imperative
- Reactive (using @wire).
This blog post dives into the imperative way, explaining its features, advantages, and use cases, with practical examples.
If you’re interested in exploring the reactive approach to calling Apex classes using @wire, check out the detailed post below:
What is the Imperative Way?
The imperative way allows developers to call Apex methods programmatically in response to specific user actions, such as button clicks or form submissions.
Unlike the reactive approach, which automatically fetches data when the component is rendered, the imperative approach gives you more control over when and how to invoke the Apex logic.
Key Features of the Imperative Way
- Flexibility: You control when the Apex method is executed.
- Conditional Execution: Useful for scenarios where Apex methods depend on user interactions or dynamic input.
- Error Handling: Allows explicit error handling using try-catch or .then and .catch.
Steps to Use Imperative Apex in LWC
1. Import the Apex Method:
- Use @salesforce/apex to import the Apex method.
import apexMethod from '@salesforce/apex/Namespace.Classname.apexMethod';
- apexMethod -This identifies the method name in Apex Class.
- Classname – This is the Apex class name.
- Namespace –The namespace of the Salesforce organization
2. Call the Apex Method:
- Use the imported apex method like a JavaScript function.
- To expose an Apex method to a Lightning web component, the method must be static and either global or public.
- Also the apex method must be annotated with @AuraEnabled.
- Unlike reactive way, we should not use @AuraEnabled(cacheable=true).
Just @AuraEnable 😊
3. Handle Results
Use .then() to process the result and .catch() to handle errors.
Example 1: Fetching Records on Button Click
Apex Class:
public with sharing class AccountController {
@AuraEnabled
public static List getAccounts() {
return [SELECT Id, Name, Industry FROM Account LIMIT 10];
}
}
LWC HTML (template):
- {account.Name} - {account.Industry}
Error: {error}
LWC JavaScript
import { LightningElement, track } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
export default class ImperativeApexExample extends LightningElement {
@track accounts;
@track error;
fetchAccounts() {
getAccounts()
.then((result) => {
this.accounts = result;
this.error = undefined;
})
.catch((error) => {
this.error = error.body.message;
this.accounts = undefined;
});
}
}
Example 2: Passing Parameters to Apex
Apex Class:
public with sharing class AccountController {
@AuraEnabled
public static List searchAccounts(String searchTerm) {
return [SELECT Id, Name FROM Account WHERE Name LIKE :('%' + searchTerm + '%')];
}
}
LWC HTML (template):
- {account.Name}
Error: {error}
LWC JavaScript
import { LightningElement, track } from 'lwc';
import searchAccounts from '@salesforce/apex/AccountController.searchAccounts';
export default class SearchAccountsImperative extends LightningElement {
@track accounts;
@track error;
searchTerm = '';
handleInput(event) {
this.searchTerm = event.target.value;
}
searchAccounts() {
searchAccounts({ searchTerm: this.searchTerm })
.then((result) => {
this.accounts = result;
this.error = undefined;
})
.catch((error) => {
this.error = error.body.message;
this.accounts = undefined;
});
}
}
Key Advantages of Imperative Apex
- Granular Control: Execute Apex methods only when needed, based on specific user actions.
- Dynamic Parameters: Easily pass parameters to Apex methods based on runtime user input.
- Enhanced Error Handling: Explicit handling of server-side errors for a better user experience.
When to Use the Imperative Way?
- User-Driven Actions: When the execution depends on explicit user interaction (e.g., button clicks).
- Dynamic Inputs: When Apex methods require dynamic parameters or conditions.
- Custom Logic: When data fetching or processing logic depends on complex conditions not suited for reactive @wire.
Key Considerations
- Governor Limits: Be mindful of Salesforce governor limits when invoking Apex methods.
- Error Handling: Always handle errors gracefully to enhance the user experience.
- Performance: Use the imperative way sparingly for large datasets to avoid performance issues.
Conclusion
The imperative way in LWC is a powerful tool that provides flexibility and control over how and when to execute server-side logic.
It’s particularly useful for user-driven actions, dynamic inputs, and scenarios requiring explicit error handling.
Explore more LWC tips and tricks on Writtee, your go-to platform for Salesforce insights! 🚀