@wire, imperative calls are triggered by user actions or component logic.
Implementation
Key Features
Imperative Call
Import and call the Apex method as a JavaScript function:Async/Await Pattern
Use async/await for cleaner asynchronous code:Error Handling
Use try/catch to handle errors:User-Triggered Execution
The method is called when the user clicks the button:Properties
| Property | Type | Description |
|---|---|---|
contacts | Array | List of contacts returned from Apex |
error | Object | Error object if the call fails |
Apex Method Requirements
For cacheable methods (read-only operations):Error Types
Common error scenarios:- No access: User lacks permission to access records
- SOQL errors: Invalid query or limits exceeded
- DML errors: Failed insert/update/delete operations
- Custom errors: Thrown by your Apex code
When to Use Imperative vs Wire
Use Imperative When:
- You need to call the method in response to user actions
- You want control over when the method executes
- You need to perform DML operations
- You want to chain multiple operations
- You need to pass dynamic parameters
Use Wire When:
- Data should load automatically
- You want reactive updates
- You’re doing read-only operations
- Parameters are reactive properties
Best Practices
- Always use try/catch: Handle errors gracefully
- Clear previous state: Reset data or error on each call
- Use async/await: Cleaner than promise chains
- Show loading state: Indicate when operation is in progress
- Handle all error cases: Provide meaningful error messages
Advanced Example with Loading State
Comparison with Wire
| Feature | Imperative | Wire |
|---|---|---|
| Execution | On-demand | Automatic |
| Control | Manual | Automatic |
| Caching | Optional | Required for cacheable |
| DML operations | Supported | Not supported |
| User action | Required | Not required |
| Reactivity | Manual | Automatic |
