Skip to main content

Salesforce

Understanding @api, @track, and @wire Decorators in Lightning Web Components (LWC)

Multiracial Portuguese Jamaican mid adult businessman with beard standing smiling at desk with laptop reviewing data in bright business office wearing suit

Introduction:

Lightning Web Components (LWC) introduced a new programming model with decorators that enhance the functionality of properties and functions. Among these decorators, @api, @track, and @wire play crucial roles in creating powerful and interactive Lightning components. In this blog, we will explore each decorator in detail and understand how they contribute to the development of Lightning Web Components.

 

  1. The @api Decorator: Exposing Public Properties

The @api decorator is used to expose public properties. This allows other components, including the owner component that includes the LWC in its markup, to access and interact with those properties.

Example:

import { LightningElement, api } from 'lwc';

export default class accountInfo extends LightningElement {

    @api firstName;

    @api lastName;

    @api email;

}

 

In the above code, the accountInfo component exposes three properties, firstName, lastName, and email, using the @api decorator. These properties can be set and accessed by other components that include the accountInfo component.

To utilize these properties, you can include the accountInfo component in another component’s markup and pass values to the firstName, lastName, and email properties:

The @api decorator ensures that any changes to these properties are propagated and reflected wherever they are used. If the values of firstName, lastName, or email are updated in the parent component, the accountInfo component will automatically receive the updated values and rerender if necessary.

 

  1. The @track Decorator: Tracking Private Reactive Properties

The @track decorator enables tracking of private reactive properties in Lightning Web Components. By decorating a private property with @track, the component becomes aware of changes to that property’s value. Whenever a tracked property is modified, the component automatically rerenders to reflect the updated value. This section will discuss the advantages and usage guidelines of @track in Lightning Web Components.

Example:

Let’s consider a scenario where we have a Lightning Web Component that displays a counter. The counter value is stored in a private property called count, and we want the component to automatically rerender whenever the count changes. To achieve this, we can use the @track decorator.

import { LightningElement, track } from 'lwc';

export default class CounterComponent extends LightningElement {

    @track count = 0;
    incrementCount() {
        this.count++;
    }

    decrementCount() {
        this.count--;
    }

}

 

In the above example, we use the @track decorator to decorate the count property. This allows the component to track changes to the count property and automatically rerender whenever its value is modified.

The component has two methods, incrementCount and decrementCount, which increase and decrease the count respectively. When either of these methods is called, the count property is updated, triggering a rerender of the component’s template to reflect the updated count.

 

  1. The @wire Decorator: Leveraging Reactive Data Fetching

The @wire decorator is used to read Salesforce data and leverage reactive data fetching in Lightning Web Components. By using @wire in the JavaScript class, a component can specify a wire adaptor or an Apex method to fetch data from Salesforce. When the wire service provisions the data, the component automatically rerenders to reflect the new data. This section will provide insights into the power and implementation considerations of using @wire in Lightning Web Components.

In the below example, we have a Lightning Web Component called BearSupervisor. It uses the @wire decorator to fetch a record and its related field value using the getRecord function from the lightning/uiRecordApi module.

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

import SUPERVISOR_FIELD from '@salesforce/schema/Bear__c.Supervisor__c';

const bearFields = [SUPERVISOR_FIELD];

export default class BearSupervisor extends LightningElement {

    @api recordId;

    @wire(getRecord, { recordId: '$recordId', fields: bearFields })

    getbear({ error, data }) {
        if (data) {
            console.log('data is: ' + JSON.stringify(data));
        } 

        else if (error) {
            console.log('error is: ' + JSON.stringify(error));
        }

    }

}

 

The @wire decorator is applied to the getbear method, which is invoked when the getRecord function retrieves the data. The @wire decorator takes two parameters: the function to call (getRecord) and an object containing the configuration options. In this case, we pass the recordId property using the binding syntax ‘$recordId’ and specify the bearFields to fetch.

 

Handling the Response:

The getbear method receives an object containing error and data as parameters. Inside the method, we check if data is available. If it exists, we log the retrieved data to the console. If there is an error, we log the error details to the console.

By using the @wire decorator in this example, the component establishes a reactive connection with the getRecord function. It fetches the record data specified by the recordId property and the desired fields. When the data is available, the component automatically rerenders, allowing you to access and process the retrieved data.

 

Conclusion:

The @api, @track, and @wire decorators in Lightning Web Components significantly enhance the functionality and interactivity of components. By using @api, developers can expose public properties, enabling component composition and communication. @track facilitates tracking of private reactive properties, ensuring automatic rerendering when their values change. Meanwhile, @wire enables reactive data fetching from Salesforce, resulting in dynamic and up-to-date components. Understanding and effectively utilizing these decorators is essential for building robust and performant Lightning Web Components.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Sanket Dudhe

Sanket Dudhe is an Associate Technical Consultant at Perficient. He has an experience of 4+ years as SDET. He loves technology and hence is curious to learn about new emerging technologies #lovefortechnology.

More from this Author

Categories
Follow Us
TwitterLinkedinFacebookYoutubeInstagram