Follow

Follow
Leveraging the Power of Decorators in Your LWC Components

Leveraging the Power of Decorators in Your LWC Components

Mastering the @api, @wire, and @track Decorators in Salesforce LWC

Christian Pelayo's photo
Christian Pelayo
ยทDec 15, 2022ยท

5 min read

Play this article

Table of contents

  • Introduction
  • @api
  • @wire
  • @track
  • Real-Life Examples
  • Conclusion
  • References

Introduction

Hello everyone! ๐Ÿ‘‹ In this blog post, we will take a closer look at the @api, @wire, and @track decorators in Salesforce Lightning Web Components (LWC). We will discuss what these decorators do, how they work, and provide some real-life examples of how they can be used in LWC components. By the end of this post, you should have a good understanding of how to leverage the power of decorators in your own LWC development. Let's get started!

Start blogging with Hashnode

Salesforce Lightning Web Components (LWC) is a modern programming model for building enterprise-grade web applications. It provides developers with a set of reusable components and tools for building responsive user interfaces.

One of the key features of LWC is its use of decorators, which are special keywords that can be used to modify a class or its properties. In this blog post, we will take a closer look at three of the most commonly used decorators in LWC: @api, @wire, and @track.

@api

The @api decorator is used to expose a public property or method on a LWC component. This allows other components to access and interact with the decorated property or method.

For example, consider the following HelloWorld component that uses the @api decorator to expose a message property:

import { LightningElement, api } from 'lwc';

export default class HelloWorld extends LightningElement {
    @api
    message = 'Hello World!';
}

This message property can now be accessed and updated by other components that use the HelloWorld component. For example, the following component could be used to update the message property of the HelloWorld component:

import { LightningElement } from 'lwc';

export default class UpdateMessage extends LightningElement {
    handleClick() {
        // Get a reference to the HelloWorld component
        const helloWorld = this.template.querySelector('c-hello-world');

        // Update the message property of the HelloWorld component
        helloWorld.message = 'Hello Salesforce!';
    }
}

@wire

The @wire decorator is used to wire a property or method in a LWC component to a data source. This allows the component to automatically receive data from the specified data source, without having to manually fetch or subscribe to the data.

For example, consider the following AccountList component that uses the @wire decorator to wire its accounts property to the @salesforce/apex/AccountController.getAccounts Apex method:

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

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

    // Other component logic...
}

This accounts property will now automatically receive a list of accounts from the getAccounts Apex method whenever the component is rendered or the data changes. The component does not need to manually call the Apex method or subscribe to any data change events.

@track

The @track decorator is used to track changes to a property in a LWC component. This allows the component to automatically rerender itself whenever the value of the decorated property changes.

For example, consider the following Counter component that uses the @track decorator to track changes to its count property:

import { LightningElement, track } from 'lwc';

export default class Counter extends LightningElement {
    @track
    count = 0;

    increment() {
        this.count++;
    }

    decrement() {
        this.count--;
    }
}

Whenever the increment or decrement method is called, the count property will be updated, and the component will automatically rerender itself to reflect the new value. This allows the component to always display the current value of the count property, without having to manually update the UI.

Real-Life Examples

Now that we have discussed the basics of the @api, @wire, and @track decorators, let's take a look at some real-life examples of how they can be used in a LWC component.

@api Example

Suppose we want to create a ProductList component that displays a list of products, and allows the user to select a specific product to view more details. We can use the @api decorator to expose a selectedProduct property on the ProductList component, which other components can use to access and update the currently selected product.

import { LightningElement, api } from 'lwc';

export default class ProductList extends LightningElement {
    @api
    selectedProduct;

    // Other component logic...
}

Another component, such as a ProductDetails component, can then access the selectedProduct property of the ProductList component to display details about the selected product.

import { LightningElement } from 'lwc';

export default class ProductDetails extends LightningElement {
    // Get a reference to the ProductList component
    productList = this.template.querySelector('c-product-list');

    // Display details about the selected product
    product = this.productList.selectedProduct;
}

@wire Example

Suppose we want to create a ContactList component that displays a list of contacts from a Salesforce account. We can use the @wire decorator to wire the contacts property of the ContactList component to the @salesforce/apex/ContactController.getContacts Apex method, which will return a list of contacts from the account.

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

export default class ContactList extends LightningElement {
    @wire(getContacts)
    contacts;

    // Other component logic...
}

The contacts property will automatically be updated whenever the list of contacts changes, so the component will always display the most up-to-date list of contacts.

@track Example

Suppose we want to create a TemperatureConverter component that allows the user to convert temperatures between Celsius and Fahrenheit. We can use the @track decorator to track changes to the temperature and unit properties of the component, which will be updated whenever the user enters a new temperature or selects a different unit.

import { LightningElement, track } from 'lwc';

export default class TemperatureConverter extends LightningElement {
    @track
    temperature = 0;

    @track
    unit = 'C';

    handleTemperatureChange(event) {
        this.temperature = event.target.value;
    }

    handleUnitChange(event) {
        this.unit = event.target.value;
    }

    convertTemperature() {
        if (this.unit === 'C') {
            this.temperature = this.temperature * (9/5) + 32;
            this.unit = 'F';
        } else {
            this.temperature = (this.temperature - 32) * (5/9);
            this.unit = 'C';
        }
    }
}

Whenever the user enters a new temperature or selects a different unit, the temperature and unit properties will be updated, and the component will automatically rerender itself to reflect the changes. This allows the component to always display the current temperature and unit, and to convert the temperature when the user clicks the "Convert" button.

Conclusion

In conclusion, the @api, @wire, and @track decorators are powerful tools that can greatly simplify the development of LWC components. By exposing public properties and methods, wiring components to data sources, and tracking changes to component properties, developers can create robust and reactive components that provide a seamless user experience.

References

Did you find this article valuable?

Support Christian Pelayo by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
ย 
Share this