Wire Service in LWC with Example

This post will explain everything you need to know about the Wire Service in LWC (Lightning Web Component) with Examples. This post will contain the implementation for both Wire Service with @wire Property and Wire Service with @wire Function.

The WIre Service provisions an immutable stream of data to the Lightning Web Component. Every value that is available in the stream is the newer version of the value that precedes it. It uses the client-cache to get the data. If the data exists in the client-cache, a network request may not be made.

How to use the @wire Service in LWC?

In order to use Wire Service in LWC, first, we need to import a wire adapter using named import syntax, like below:

import { getRecord } from 'lightning/uiRecordApi';
import accounts from '@salesforce/apex/AccountController.getAccounts';

Here, getRecord and accounts are called as adapterId. Whereas, uiRecordApi and Apex are called as adapterModule.

Syntax for Wire Service looks something like below:

import { adapterId } from 'adapterModule';
@wire(adapterId, adapterConfig)
propertyOrFunction;

Where,

  • adapterId: Identifier for the wire adapter.
  • adapterModule: Identifier of the module that contains the wire adapter functions, in the format namespace/moduleName.
  • adapterConfig: Configuration object to wire function to provide parameters to functions. Make sure to not update a wire adapter configuration object property in renderedCallback() as it can result in an infinite loop.
  • propertyOrFunction: A private property or function that receives the stream of data from the wire service.

Implementation

In this implementation, we will use Wire Service with both property and function to display a list of Accounts.

Wire Service with @wire Property

It is useful when we want to consume the data or error as it is. Wire property is partially Reactive because it supports reactive variables, which are prefixed with $.

The object assigned as wire property has two variables:

  • data: Value supplied by the adapter.
  • error: Error if the adapter wasn’t able to supply any data.

By default, these variable of property are undefined.

Consider below example:

wireService,js

import { LightningElement, wire } from 'lwc';
import accounts from '@salesforce/apex/AccountController.getAccounts';
export default class WireService extends LightningElement {
    strSearchText;
    @wire (accounts, {strName:'$strSearchText'})
    lstAccount;
    changeSearchText(event){
        this.strSearchText = event.target.value;
    }
}

First, we imported accounts adapterId (which is the Apex method in this case) from apex adapter module. Then, we used the wire decorator for lstAccount property where the first parameter is the accounts adapterId. In the configuration parameter, we are passing strName which is the only parameter for getAccounts Apex method.

We have assigned strSearchText with $ to strName to make it Reactive. Hence, every time strSearchText is updated, Wire Service will call the Apex method to get the latest data and store it in lstAccount. Then, we can use lstAccount.data to access those records.

wireService.html

<template>
    <lightning-card title="Search Accounts">
        <lightning-layout>
            <lightning-layout-item size="6">
                <!-- Displaying Accounts. -->
                <div class="slds-p-left_medium">
                    <lightning-input placeholder="Enter Account Name" onchange={changeSearchText}></lightning-input>
                    <br/>
                    
                    <!-- To display accounts if list is not null-->
                    <template for:each={lstAccount.data} for:item="acc">
                        <div key={acc.Id} class="slds-p-around_medium lgc-bg">
                            <lightning-tile label={acc.Name} type="media">
                                <lightning-icon slot="media" icon-name="standard:groups"></lightning-icon>
                                <p class="slds-truncate">
                                    <lightning-formatted-text value={acc.AccountNumber}></lightning-formatted-text>
                                </p>
                            </lightning-tile>
                        </div>
                    </template>
                    
                </div>
            </lightning-layout-item>
        </lightning-layout>
    </lightning-card>
</template>

Above is the HTML file which contains the markup to display textbox and list of Accounts. Once the value is entered in the textbox, onchange event will trigger and the changeSearchText method will update the strSearchText. This will trigger the Wire Service and loads the Accounts in lstAccount.

Also Read : Multiple Ways to Call Apex Method from Lightning Web Component

Wire Service with @wire Function

It is useful when we want to perform some logic when new data is provided or an error occurs. Wire function has two parameters; error and data, just like a wired property. The function is executed whenever a value is available.

Consider below example:

wireService.js

import { LightningElement, wire } from 'lwc';
import accounts from '@salesforce/apex/AccountController.getAccounts';
export default class WireService extends LightningElement {
    lstAccount = [];
    strSearchText;
    @wire (accounts, {strName:'$strSearchText'})
    fetchAccount({error, data}){
        if(data){
            this.lstAccount = data; 
        }else if(error){
            console.log(error);
        }
    };
    changeSearchText(event){
        this.strSearchText = event.target.value;
    }
}

Everything is the same, except for the wire property. Instead, we have a wire function fetchAccount. The two parameters to this function are error and data, which will work in the same way.

In the HTML file, we need to access the Accounts using lstAccount rather than lstAccount.data. Because we are assigning data to lstAccount property. The rest of the code will be the same.

AccountController.cls

public class AccountController {
     
    @AuraEnabled(cacheable=true)
    public static list<Account> getAccounts(String strName){
        String strNameLike = '%' +strName +'%';
        return [SELECT Name, AccountNumber FROM Account WHERE Name LIKE :strNameLike];
    }
}

@wire Service in LWC with Example

This is how our output will look:

Wire Service in LWC
Wire Service in LWC

This is how we can use @wire service in LWC.

That is all from this post. If you don’t want to miss new implementations, please Subscribe here.

If you want to check more implementation using Lightning Web Components, you can check it here.

Check official Salesforce documentation to know more about Wire Service here.

Leave a Comment