Mastering the @wire Decorator in Salesforce LWC: A Comprehensive Guide with Examples

@wire decorator in LWC
Chinmaya By Chinmaya
6 Min Read

Introduction

The @wire decorator in Salesforce Lightning Web Components (LWC) is a powerful tool for accessing data from Salesforce database, such as Apex methods or Salesforce’s built-in wire adapters.

It simplifies the process of fetching, caching, and updating data within your components.

In this blog post, we will understand the @wire decorator, its use cases, syntax, and practical examples, helping you leverage its potential in Salesforce development.

If you’re unfamiliar with Decorators, I recommend checking out the posts below to learn about the different types of LWC decorators in Salesforce.

What is the @wire decorator?

    • Wire decorator is used to read data from Salesforce database by connecting your LWC component to Salesforce data source.
    • Wire decorator is reactive in nature, which means – whenever the data in Salesforce org changes, then automatically the component re-renders and the updated data is displayed on the LWC component.

The @wire decorator can be applied to:

    1. Properties: Automatically receives and holds data for use in the component.
    2. Functions: Offers more flexibility to process or manipulate the fetched data.

Common Use Cases for @wire

    1. Fetching Salesforce data using wire adapters (e.g., getRecord, getListUi).
    2. Invoking Apex methods for custom business logic.
    3. Leveraging Lightning Data Service (LDS) for declarative access to Salesforce records.
    4. Optimizing data caching for better performance and efficiency.

Syntax

				
					import { LightningElement, wire } from ‘lwc’;

import <methodName> from ‘@salesforce/apex/<ApexClassName.apexMethod>’;

@wire(methodName, {methodParams})
				
			
    1. methodName – It identifies the apex method.
    2. ApexClassName – It is the apex class name
    3. apexMethod – Method of apex class

1. Using @wire with a Property

				
					@wire(wireAdapter, config)
propertyName;
				
			

2. Using @wire with a Function

				
					@wire(wireAdapter, config)
wiredFunction({ error, data }) {
    // Handle data or error
}
				
			

Example 1: Using @wire with getRecord to Fetch a Record

This example demonstrates how to use @wire to fetch a Salesforce record.

JavaScript: exampleComponent.js

				
					import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';

// Specify the fields to fetch
const FIELDS = ['Account.Name', 'Account.Industry', 'Account.Phone'];

export default class ExampleComponent extends LightningElement {
    @api recordId; // Record ID passed from parent or environment

    @wire(getRecord, { recordId: '$recordId', fields: FIELDS })
    account;

    get accountName() {
        return this.account.data ? this.account.data.fields.Name.value : 'N/A';
    }

    get accountIndustry() {
        return this.account.data ? this.account.data.fields.Industry.value : 'N/A';
    }

    get accountPhone() {
        return this.account.data ? this.account.data.fields.Phone.value : 'N/A';
    }
}
				
			

HTML: exampleComponent.html

				
					<div>
    <p>Account Name: {accountName}</p>
    <p>Industry: {accountIndustry}</p>
    <p>Phone: {accountPhone}</p>
</div>
				
			

Example 2: Using @wire with Apex

This example shows how to call an Apex method using @wire.

Apex Class: AccountController.cls

				
					public with sharing class AccountController {
    @AuraEnabled(cacheable=true)
    public static List<Account> getRecentAccounts() {
        return [SELECT Id, Name, Industry FROM Account ORDER BY CreatedDate DESC LIMIT 5];
    }
}
				
			

JavaScript: exampleComponent.js

				
					import { LightningElement, wire } from 'lwc';
import getRecentAccounts from '@salesforce/apex/AccountController.getRecentAccounts';

export default class ExampleComponent extends LightningElement {
    accounts;
    error;

    @wire(getRecentAccounts)
    wiredAccounts({ error, data }) {
        if (data) {
            this.accounts = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.accounts = undefined;
        }
    }
}
				
			

HTML: exampleComponent.html

				
					<template>
    <div>
        <template if:true={accounts}>
            <ul>
                <template for:each={accounts} for:item="account">
                    <li key={account.Id}>{account.Name} - {account.Industry}</li>
                </template>
            </ul>
        </template>
        <template if:true={error}>
            <p>Error: {error.body.message}</p>
        </template>
    </div>
</template>
				
			

Key Points About @wire

    1. Declarative Data Fetching: Simplifies data fetching by binding directly to a wire adapter or Apex method.
    2. Automatic Caching: Automatically caches data for improved performance. Use the @AuraEnabled(cacheable=true) annotation for Apex methods to take advantage of this feature.
    3. Error Handling: Provides built-in error handling through { error, data } structure.
    4. Reactivity: Automatically re-fetches data if the dynamic parameters in the wire configuration change.
    5. Read-Only Data: Data retrieved via @wire is read-only; to modify it, create a mutable copy.

When to Use @wire

    1. Fetching frequently accessed Salesforce records or lists.
    2. Using built-in wire adapters like getRecord, getObjectInfo, or getPicklistValues.
    3. Calling Apex methods for custom logic while leveraging caching.
    4. Reacting to changes in parameters dynamically.

Limitations of @wire

    1. Cannot use @wire for imperative calls; use the standard Apex invocation pattern (@AuraEnabled) instead.
    2. Data is read-only and cannot be directly mutated.

Checkout below posts to explore other 2 LWC Decorators in Salesforce

Conclusion

The @wire decorator is an important tool for Salesforce LWC developers, enabling seamless integration with Salesforce data and services.

Its declarative approach simplifies data handling while enhancing performance through caching and reactivity.

For more expert content on Salesforce development, visit Writtee.com. Let us know in the comments how you’ve used @wire in your projects.

Happy coding! 🚀

Share This Article
Follow:
Chinmaya is working as a Senior Consultant with a deep expertise in Salesforce. Holding multiple Salesforce certifications, he is dedicated to designing and implementing cutting-edge CRM solutions. As the creator of Writtee.com, Chinmaya shares his knowledge on educational and technological topics, helping others excel in Salesforce and related domains.
3 Comments