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

@wire decorator in LWC
Chinmaya By Chinmaya
7 Min Read

Introduction

In Lightning Web Components (LWC), a wire adapter is a mechanism that allows you to read Salesforce data or call Apex methods in a reactive and declarative way.
Wire adapters are part of the Lightning Web Components framework and are designed to simplify data access and management.

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.

Key Concepts of Wire Adapters

1. Declarative Data Fetching:

  • Wire adapters enable you to fetch data from Salesforce (e.g., records, metadata, or Apex methods) without writing imperative code (e.g., @api or async/await).

  • You declare what data you need, and the framework handles the rest.

2. Reactive:

  • Wire adapters are reactive, meaning they automatically update when the underlying data changes or when the component’s properties change.

3. Caching:

  • Wire adapters leverage the Lightning Data Service (LDS) cache, which improves performance by reducing server calls.

4. No Boilerplate Code:

  • Wire adapters eliminate the need for boilerplate code like then/catch for promises or try/catch for async/await.

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.

Types of Wire Adapters

1. Built-in Wire Adapters:

  • Salesforce provides several built-in wire adapters for common use cases, such as:

    • getRecord: Fetches a single record.

    • getObjectInfo: Retrieves metadata about an object.

    • getPicklistValues: Fetches picklist values for a field.

    • getListUi: Retrieves list views for an object.

2. Custom Wire Adapters:

  • You can create custom wire adapters using Apex methods annotated with @AuraEnabled(cacheable=true).

How to Use a Wire Adapter?

1. Import the Wire Adapter

  • Use the @wire decorator to import the wire adapter in your JavaScript file.

  • Example:

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

2. Declare the Wire Adapter

  • Use the @wire decorator to declare the wire adapter and specify the data you need.

  • Example:

				
					export default class MyComponent extends LightningElement {
    @wire(getRecord, { recordId: '001XXXXXXXXXXXXXXX', fields: ['Account.Name'] })
    account;
}
				
			

3. Access the Data

  • The data returned by the wire adapter is stored in a property (e.g., account).

  • You can access the data in your HTML template or JavaScript.

  • Example:

				
					<template>
    <template if:true={account.data}>
        <p>Account Name: {account.data.fields.Name.value}</p>
    </template>
    <template if:true={account.error}>
        <p>Error: {account.error}</p>
    </template>
</template>
				
			

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, wire, api } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';

export default class MyComponent extends LightningElement {
    @api recordId; // Record ID passed from the parent component or page

    @wire(getRecord, { recordId: '$recordId', fields: ['Account.Name', 'Account.Industry'] })
    account;

    get name() {
        return this.account.data ? this.account.data.fields.Name.value : '';
    }

    get industry() {
        return this.account.data ? this.account.data.fields.Industry.value : '';
    }
}
				
			

HTML: exampleComponent.html

				
					<template>
    <template if:true={account.data}>
        <p>Account Name: {name}</p>
        <p>Industry: {industry}</p>
    </template>
    <template if:true={account.error}>
        <p>Error: {account.error}</p>
    </template>
</template>
				
			

Example 2: Using a Custom Wire Adapter 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> getAccounts() {
        return [SELECT Id, Name FROM Account LIMIT 10];
    }
}
				
			

JavaScript: exampleComponent.js

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

export default class MyComponent extends LightningElement {
    @wire(getAccounts)
    accounts;

    get hasAccounts() {
        return this.accounts.data && this.accounts.data.length > 0;
    }
}
				
			

HTML: exampleComponent.html

				
					<template>
    <template if:true={hasAccounts}>
        <template for:each={accounts.data} for:item="account">
            <p key={account.Id}>{account.Name}</p>
        </template>
    </template>
    <template if:true={accounts.error}>
        <p>Error: {accounts.error}</p>
    </template>
</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.
5 Comments