Skip to main content
This component demonstrates how to wire an Apex method to a function instead of a property. This approach gives you more control over data processing and state management.

Implementation

import { LightningElement, wire } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';

export default class ApexWireMethodToFunction extends LightningElement {
    contacts;
    error;

    @wire(getContactList)
    wiredContacts({ error, data }) {
        if (data) {
            this.contacts = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.contacts = undefined;
        }
    }
}

Key Features

Wire to Function

The @wire decorator binds the Apex method to a function that receives data and error:
@wire(getContactList)
wiredContacts({ error, data }) {
    if (data) {
        this.contacts = data;
        this.error = undefined;
    } else if (error) {
        this.error = error;
        this.contacts = undefined;
    }
}

Separate Properties

Manage contacts and error as separate reactive properties:
contacts;
error;

Data Processing

The function allows you to:
  • Transform data before storing it
  • Perform calculations or filtering
  • Manage multiple properties
  • Add custom logic based on response

Error Handling

Explicitly handle errors and clear previous states:
if (error) {
    this.error = error;
    this.contacts = undefined; // Clear previous data
}

Advantages Over Property Binding

  1. Data Transformation: Process data before assigning to properties
  2. State Control: Explicitly manage when to clear or update state
  3. Custom Logic: Add business logic in the response handler
  4. Multiple Properties: Update multiple properties from single response

When to Use

Use this pattern when:
  • You need to transform or process data before display
  • You want explicit control over state management
  • You need to update multiple properties
  • You want to add custom error handling logic

Comparison with Property Binding

FeatureProperty BindingFunction Binding
Code simplicitySimpleModerate
Data processingNoneFull control
State managementAutomaticManual
Error handlingBuilt-inCustom
Use caseSimple displayComplex logic

Build docs developers (and LLMs) love