Skip to main content
Lightning Web Components can call Apex methods to interact with Salesforce data and business logic. You can use either the @wire decorator for reactive data or call methods imperatively for user-initiated actions.

Apex Controller Setup

Create Apex methods with the @AuraEnabled annotation. Use cacheable=true for read-only methods that can be cached.

Apex Method Requirements

  • Methods must be static
  • Annotate with @AuraEnabled
  • Use cacheable=true for read-only methods
  • Use WITH USER_MODE to enforce sharing rules and field-level security
  • Classes should use with sharing to enforce record-level security

Wire Service Approach

Use @wire for methods that load data automatically when a component initializes or when reactive parameters change.

Wire to Property

The simplest approach for displaying data without transformation.
When to use:
  • Simple data display
  • No data transformation needed
  • Minimal error handling
Access the data:

Wire to Function

Provides more control for processing results and handling errors.
When to use:
  • Data transformation required
  • Custom error handling
  • Setting multiple properties
  • Conditional logic based on results

Imperative Approach

Call Apex methods imperatively for user-triggered actions like button clicks.
When to use:
  • User-initiated actions (button clicks, form submissions)
  • Multiple sequential Apex calls
  • Conditional Apex calls
  • Need to call methods dynamically

Parameters

Pass parameters to Apex methods using an object:

Comparison: Wire vs Imperative

Advantages:
  • Automatic caching
  • Reactive to parameter changes
  • No manual lifecycle management
  • Shared cache across components
Best for:
  • Loading data on component initialization
  • Reactive data that updates with parameters
  • Read-only operations

Error Handling

Best Practices

Use Cacheable

Set cacheable=true on read-only Apex methods for better performance

Enforce Security

Always use WITH USER_MODE and with sharing to respect user permissions

Choose the Right Approach

Use @wire for automatic loading, imperative for user actions

Handle Errors

Always implement error handling for better user experience