Friday, December 16, 2022

wire Service LWC Lightning Web Component

wire Service LWC Lightning Web Components(LWC)

@wire Service LWC

Lightning web components(LWC) use a reactive wire service, which is built on Lightning Data Service. Components use @wire in their JavaScript class to read data from one of the wire adapters in the lightning/ui*Apimodules and also to call the apex controller server-side methods using wire services. The wire service provisions an immutable stream of data to the component. Each value in the stream is a newer version of the value that precedes it.

We call the wire service reactive in part because it supports reactive variables, which are prefixed with $. If a reactive variable changes, the wire service provisions new data. We say “provisions” instead of “requests” or “fetches” because if the data exists in the client cache, a network request may not be involved. The wire service delegates control flow to the Lightning Web Components engine. Delegating control is great for read operations, but it isn’t great for create, update, and delete operations. As a developer, you want complete control over operations that change data. That’s why you perform create, update, and delete operations with a JavaScript API instead of with the wire service.

Wire Service Syntax

Import a wire adapter using named import syntax.

1
import { wire} from 'lwc';

Decorate a property or function with @wire and specify the wire adapter.

1
2
@wire(adapterId, adapterConfig)
propertyOrFunction;

Here is full code syntax and its detail for using wire

1
2
3
import { wire} from 'lwc';
@wire(adapterId, adapterConfig)
propertyOrFunction;
  • adapterId (Identifier)—The identifier of the wire adapter.
  • adapterModule (String)—The identifier of the module that contains the wire adapter function, in the format namespace/moduleName. Look at the format! To import a module in JavaScript, use lightning/ui*Api instead of lightning-ui-*-api.
  • adapterConfig (Object)—A configuration object specific to the wire adapter. Configuration object property values can be either strings or references to objects and fields imported from @salesforce/schema. Properties in the adapterConfig object can’t be undefined. If a property is undefined, the wire service doesn’t provision data. Don’t 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. If a property is decorated with @wire, the results are returned to the property’s data property or error property. If a function is decorated with @wire, the results are returned in an object with a data property and an error property.

 

Import References to Salesforce Objects and Fields

When you use a wire adapter in a lightning/ui*Api module, we strongly recommend importing references to objects and fields. Salesforce verifies that the objects and fields exist, prevents objects and fields from being deleted, and cascades any renamed objects and fields into your component’s source code. It also ensures that dependent objects and fields are included in change sets and packages. Importing references to objects and fields ensures that your code works, even when object and field names change.

If a component isn’t aware of which object it’s using, use strings instead of imported references. Use getObjectInfo to return the object’s fields. All wire adapters in the lightning/ui*Api modules respect object CRUD rules, field-level security, and sharing. If a user doesn’t have access to a field, it isn’t included in the response.

To import a reference to an object, use this syntax.


import objectName from '@salesforce/schema/object';
import objectName from '@salesforce/schema/namespace__object';
 
import POSITION_OBJECT from '@salesforce/schema/Position__c';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';

 

To import a reference to a field, use this syntax.


import FIELD_NAME from '@salesforce/schema/object.field';
 
import POSITION_LEVEL_FIELD from '@salesforce/schema/Position__c.Level__c';
import ACCOUNT_NAME_FIELD from '@salesforce/schema/Account.Name';

 

To import a reference to a field via a relationship, use this syntax. You can use relationship fields to traverse to parent objects and fields. You can specify up to three relationship fields, which results in four objects and the field being referenced. For example, Opportunity.Account.CreatedBy.LastModifiedById returns 4 levels of spanning fields.


import SPANNING_FIELD_NAME from '@salesforce/schema/object.relationship.field';
 
import POSITION_HIRINGMANAGER_NAME_FIELD__c from '@salesforce/schema/Position__c.HiringManager__r.Name__c';
import ACCOUNT_OWNER_NAME_FIELD from '@salesforce/schema/Account.Owner.Name';

 

This code imports the Account.Name field and uses it in a wire adapter’s configuration object.


import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import ACCOUNT_NAME_FIELD from '@salesforce/schema/Account.Name';
 
export default class Record extends LightningElement {
    @api recordId;
    @wire(getRecord, { recordId: '$recordId', fields: [ACCOUNT_NAME_FIELD] })
    record;
}

This code is almost identical, but it uses a string to identify the Account.Name field. This code doesn’t get the benefits that you get from importing a reference to the field.


import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
 
export default class Record extends LightningElement {
    @api recordId;
    @wire(getRecord, { recordId: '$recordId', fields: ['Account.Name'] })
    record;
}

Mark a Configuration Object Property as Dynamic and Reactive

n the wire adapter’s configuration object, prefix a value with $ to reference a property of the component instance. The $ prefix tells the wire service to treat it as a property of the class and evaluate it as this.propertyName. The property is reactive. If the property’s value changes, new data is provisioned and the component rerenders.

In this example, $recordId is dynamic and reactive.


import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
const FIELDS = [
    'Contact.Name',
    'Contact.Title',
    'Contact.Phone',
    'Contact.Email',
];
export default class WireGetRecordDynamicContact extends LightningElement {
    @api recordId;
    @wire(getRecord, { recordId: '$recordId', fields: FIELDS })
    contact;
    get name() {
        return this.contact.data.fields.Name.value;
    }
    get title() {
        return this.contact.data.fields.Title.value;
    }
    get phone() {
        return this.contact.data.fields.Phone.value;
    }
    get email() {
        return this.contact.data.fields.Email.value;
    }
}

Decorate a Property with @wire

Wiring a property is useful when you want to consume the data or error as-is.

If the property decorated with @wire is used as an attribute in the template and its value changes, the wire service provisions the data and triggers the component to rerender. The property is private, but reactive.

This code applies @wire to the record property.


import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import ACCOUNT_NAME_FIELD from '@salesforce/schema/Account.Name';
export default class Record extends LightningElement {
    @api recordId;
    @wire(getRecord, { recordId: '$recordId', fields: [ACCOUNT_NAME_FIELD] })
    record;
}

Decorate a Function with @wire

Wiring a function is useful to perform logic whenever new data is provided or when an error occurs. The wire service provisions the function an object with error and data properties, just like a wired property.

The function is invoked whenever a value is available, which can be before or after the component is connected or rendered.

wire Service LWC Example by decorating a Function with @wire

wireFunctionLWC.js


// WireFunctionLWC.js
import { LightningElement, api, track, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
export default class WireFunctionLWC extends LightningElement {
    @api recordId;
    @track record;
    @track error;
    @wire(getRecord, { recordId: '$recordId', fields: ['Account.Name'] })
    wiredAccount({ error, data }) {
        if (data) {
            this.record = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.record = undefined;
        }
    }
    get name() {
        return this.record.fields.Name.value;
    }
}

wireFunctionLWC.html


template>
    <lightning-card title="Wire Function" icon-name="standard:account">
        <template if:true={record}>
            <div class="slds-m-around_medium">
                <p>{name}</p>
            </div>
        </template>
        <template if:true={error}>
            {error}
        </template>
    </lightning-card>
</template>

wireFunctionLWC.js-meta.xml


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

 

Now we can add this lwc component on the account detail page.

  • Go to Home page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your wireFunctionLWC component and drag it on Account detail page.
  • Click Save and activate.

We will have the following output.

wire Service LWC

 

Call Apex Methods using wire

Lightning web components can import methods from Apex classes into the JavaScript classes. Once after importing the apex class method you can able call the apex methods as functions into the component by calling either via the wire service or imperatively. The Apex Method should be marked with @AuraEnabled. Before you use an Apex method, make sure that there isn’t an easier way to get the data. See whether a base Lightning component, like lightning-record-form, lightning-record-view-form, or lightning-record-edit-form works for your use case. If they don’t give you enough flexibility, use a wire adapter like getListUi or getRecordUi. And if you can’t use a wire adapter, write an Apex method.

Apex wire Import Syntax

We need to import the @salesforce/apex scoped module into JavaScript controller class.

1
import apexMethodName from '@salesforce/apex/Namespace.Classname.apexMethodReference';

Here is list of important point of importing apex method:

  • apexMethodName : An imported symbol that identifies the Apex method.
  • apexMethodReference : The name of the Apex method to import.
  • Classname : The name of the Apex class.
  • Namespace—The namespace of the Salesforce organization. Specify a namespace unless the organization uses the default namespace (c), in which case don’t specify it.

 

Most of the information in this article is copied from the official link. For more details about wire Service LWC please refer official link.

No comments:

Post a Comment