LWC Interview Questions Part-2


lightning/ui*Api Wire Adapters and Functions :

  • These modules are built on top of Lightning Data Service (LDS) and User Interface API.
  • Use these wire adapters and functions to work with Salesforce data and metadata.
  • User Interface API supports all custom objects and many standard objects.[Note : External objects are not supported]

lightning/uiListApi : (Beta version)

Get the records and metadata for a list view.

lightning/uiObjectInfoApi :

Get object metadata, and get picklist values.

Method 1 : getObjectInfo —

Use this wire adapter to get metadata about a specific object. The response includes metadata describing fields, child relationships, record type, and theme.
Syntax :
import { LightningElement, wire } from 'lwc';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';

export default class Example extends LightningElement {
    @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
    propertyOrFunction;
}
UI API Resource :
GET /ui-api/object-info/{objectApiName}
Parameters
objectApiName—(Required) A supported object.
property Or Function—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.
Returns
dataObject Info
errorFetchResponse

Method 2 : getPicklistValues —

Use this wire adapter to get the picklist values for a specified field.
Syntax :
import { LightningElement, wire } from 'lwc';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';

export default class Example extends LightningElement {
    @wire(getPicklistValues, { recordTypeId: '012000000000000AAA', fieldApiName: INDUSTRY_FIELD })
    propertyOrFunction;
}
UI API Resource :
GET /ui-api/object-info/{objectApiName}/picklist-values/{recordTypeId}/{fieldApiName}
Parameters
recordTypeId—(Required) The ID of the record type. Use the Object Info defaultRecordTypeId property, which is returned from [getObjectInfo](<https://developer.salesforce.com/docs/component-library/documentation/en/lwc/reference_wire_adapters_object_info.html>) or [getRecordUi](<https://developer.salesforce.com/docs/component-library/documentation/en/lwc/reference_wire_adapters_record_ui.html>).
fieldApiName—(Required) The API name of the picklist field on a supported object.
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.
Returns
dataPicklist Values
errorFetchResponse

Method 3 : getPicklistValuesByRecordType —

Use this wire adapter to get the values for every picklist of a specified record type.
Syntax :
import { LightningElement, wire } from 'lwc';
import { getPicklistValuesByRecordType } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';

export default class Example extends LightningElement {
    @wire(getPicklistValuesByRecordType, { objectApiName: ACCOUNT_OBJECT, recordTypeId: '012000000000000AAA' })
    propertyOrFunction}
UI API Resource
GET /ui-api/object-info/{objectApiName}/picklist-values/{recordTypeId}
Parameters
objectApiName—(Required) The API name of a supported object.
recordTypeId—(Required) The ID of the record type. Use the Object Info defaultRecordTypeId property, which is returned from [getObjectInfo](<https://developer.salesforce.com/docs/component-library/documentation/en/lwc/reference_wire_adapters_object_info.html>) or [getRecordUi](<https://developer.salesforce.com/docs/component-library/documentation/en/lwc/reference_wire_adapters_record_ui.html>).
property Or Function—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.
Returns
dataPicklist Values Collection
errorFetchResponse

lightning/uiRecordApi :

https://www.youtube.com/watch?v=NiD-fWaqMIU
[Create Record Without APEX Call Using lightning/UiRecordApi | Lightning Web Component Part 12]
This module includes wire adapters to record data and get default values to create records. It also includes JavaScript APIs to create, delete, update, and refresh records.

Method 1 : createRecord(recordInput) —

Used to create a record without calling Apex.
Syntax :
import { createRecord } from 'lightning/uiRecordApi';
createRecord(recordInput: Record): Promise<Record>
recordInput—(Required) A RecordInput object used to create the record.

Method 2 : createRecordInputFilteredByEditedFields(recordInput, originalRecord) —

Used to creates a RecordInput object with a list of fields that have been edited from their original values to pass in a call to updateRecord(recordInput).

Method 3 : generateRecordInputForCreate(record,objectInfo) —

Generates a representation of a record (Record Input) that can be used to create a record using createRecord(RecordInput). Passing in ObjectInfo filters the Record Input to only fields that are creatable.

Method 4 : generateRecordInputForUpdate(record, objectInfo) —

Generates a representation of a record (Record Input) that can be used to update a record using updateRecord(recordInput). Passing in ObjectInfo filters the Record Input to only fields that are updatable.

Method 5 : deleteRecord(recordId) —

Syntax :
import { deleteRecord } from 'lightning/uiRecordApi';
deleteRecord(recordId: string): Promise<void>

Method 6 : getFieldValue(record, field) —

Gets a field’s value from a record. Spanning fields are supported.
The field’s value is returned in its raw data form.
Syntax :
import { getFieldValue } from 'lightning/uiRecordApi';
getFieldValue(record: Record, field: string
Parameters
**record—**(Required) A Record object from which to retrieve the field value.
**field—**(Required) The API name of the field. The value can be either a string or reference to a field imported from @salesforce/schema. You can specify up to 5 levels of spanning fields.
For example, Opportunity.Account.CreatedBy.LastModifiedById returns 4 levels of spanning fields.

Method 7 : getFieldDisplayValue(record, field) —

Gets the display value of a field. Spanning fields are supported.
The display value provides formatted and localized values based on the org’s locale settings.
Syntax :
import { getFieldDisplayValue } from 'lightning/uiRecordApi';
getFieldDisplayValue(record, field)
Parameters
record—(Required) A Record object from which to retrieve the field value.
field—(Required) The API name of the field. The value can be either a string or reference to a field imported from @salesforce/schema. You can specify up to 5 levels of spanning fields.
For example, Opportunity.Account.CreatedBy.LastModifiedById returns 4 levels of spanning fields.

Method 8 : getRecord —

Syntax :
import { getRecord, getFieldValue } from **'lightning/uiRecordApi'**; import Id from **'@salesforce/user/Id'**; import NAME_FIELD from **'@salesforce/schema/User.Name'**;
Parameters details :
Get a Record | User Interface API Developer Guide | Salesforce Developers

Method 9 : getRecordCreateDefaults —

Use this wire adapter to get default information and data needed to create a record.
Syntax :
import { getRecordCreateDefaults } from 'lightning/uiRecordApi';
@wire(getRecordCreateDefaults, { objectApiName: string })
propertyOrFunction;
Parameters
objectApiName— (Required) A supported object.
formFactor— (Optional) The layout display size for the record.
An array containing any of these values:
Large—(Default) Use this value to get a layout for desktop display size.
Medium—Use this value to get a layout for tablet display size.
Small—Use this value to get a layout for phone display size.To get a value to pass as the formFactor, use the [@salesforce/client/formFactor](<https://developer.salesforce.com/docs/component-library/documentation/en/lwc/create_client_form_factor.html>) module.
recordTypeId— (Optional)The ID of the record type (RecordType object) for the new record. If not provided, the default record type is used.
optionalFields— (Optional) An array of fields to return along with the default fields. If an optional field is accessible to the context user, it’s included in the response. If it isn’t accessible to the context user, it isn’t included in the response, but it doesn’t cause an error.
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.
Returns
dataRecord DefaultsIn the response, don’t use the recordTypeInfo property. Instead, use the recordTypeId property, which is returned for every record.
errorFetchResponse
Usage
To create UI that lets a user create a record, first get information about which fields are required. This adapter’s response contains the default field values for a new record of the object type specified in {apiName}.
It also contains object metadata and the corresponding layout for Create mode. In the Salesforce user interface, an admin with “Customize Application” permission can mark a field as required in a layout. When you’re building UI, to determine which fields to mark as required in a layout for create and update, use the ObjectInfo.fields[fieldName].required property.

Method 10 : getRecordUi —

Use this wire adapter to get layout information, metadata, and data to build UI for one or more records.
Syntax :
import { LightningElement, wire } from 'lwc';
import { getRecordUi } from 'lightning/uiRecordApi';

export default class Example extends LightningElement {
  @wire(getRecordUi, { recordIds: string|string[], layoutTypes: string|string[],
                       modes: string|string[], optionalFields?: string|string[] })
  propertyOrFunction;
}
Parameters
recordIds— (Required) IDs of records to load. A string or an array of strings. All record IDs must be from a supported object.
layoutTypes—(Required) Layout types for the record. A string or an array of strings. Each string is one of these values:
Compact—Use this value to get a layout that contains a record’s key fields.
Full—Use this value to get a full layout.
modes—(Required) The access mode for the record. This value determines which fields to get from a layout. Layouts have different fields for create, edit, and view modes.
For example, formula fields are rendered in view mode, but not in create mode because they’re calculated at run time, like formulas in a spreadsheet.A string or an array of strings. Each string contains one of these values:
Create—Use this mode if you intend to build UI that lets a user create a record.
Edit—Use this mode if you intend to build UI that lets a user edit a record.
View—Use this mode if you intend to build UI that displays a record.
optionalFields—(Optional) An optional field name or an array of optional field names. If a field is accessible to the context user, it’s included in the response. If a field isn’t accessible to the context user, it isn’t included in the response, but it doesn’t cause an error.
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.
Returns
dataRecord UIIn the response, don’t use the recordTypeInfo property. Instead, use the recordTypeId property, which is returned for every record.
error[FetchResponse](<https://developer.salesforce.com/docs/component-library/documentation/en/lwc/data_error.html>)
Usage
Before you use this wire adapter, consider using the [lightning-record-*-form components](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/data_get_user_input.html). Alternatively, if you need only record data without layout information or object metadata, consider using the getRecord wire adapter.

Method 11 : updateRecord(recordInput, clientOptions) —

Updates a record. Provide the record Id of the record to update in recordInput.
Syntax :
import { updateRecord } from 'lightning/uiRecordApi';
updateRecord(recordInput: Record, clientOptions?: Object): Promise<Record>
Parameters
recordInput— (Required) A RecordInput object used to update the record. To create the object, call [generateRecordInputForUpdate(record, objectInfo)](<https://developer.salesforce.com/docs/component-library/documentation/en/lwc/reference_generate_record_input_update.html>).
Alternatively, create the RecordInput object by passing in the fields and their values. See the Usage section.
clientOptions— (Optional) To check for conflicts before you update a record, pass
const clientOptions = {'ifUnmodifiedSince' : lastModifiedDate}.
Get lastModifiedDate via a wire service adapter that returns a record object:
const lastModifiedDate = record.fields.LastModifiedDate.value;.
Returns
A Promise object that resolves with the updated record. The record contains data for the fields in the record layout.
Usage
Before you use this wire adapter, make sure that there isn’t an easier way to update the data. To create a form for working with records, consider the [lightning-record-*-form components](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/data_get_user_input.html).

@salesforce Module :

Modules scoped with @salesforce add functionality to Lightning web components at runtime.
Modules have a dynamic set of module identifiers. The set is defined by the organization’s metadata. For example, @salesforce/schema accesses an organization’s objects and fields.
Additional Important info :
@salesforce Modules
Lightning locker :
  • Ensures all Lightning Component runs in Strict mode. (summer 17)
    • Catch undeclare variable
    • Helps to Prevent cross-site script attack
    • Allow Safe access to the third-party JavaScript library
  • Can copy the code and click the EVALUATE button whether that code is compatible with the lightning locker.
4-Aug-2018
What is Client side caching in lightning?
Caching data at the client side can significantly reduce the number of server round-trips and improve the performance of your Lightning components. Using the Lightning Component Framework, you can access server data using either server actions or the Lightning Data Service. Server actions support optional client-side caching, and the Lightning Data Service is built on top of a sophisticated client caching mechanism. In this article, we focus on server actions and explore how to use them to cache the response of server method calls at the client-side and improve the performance of your application.
In Lightning terminology, a server action is an Apex method that you invoke remotely from your Lightning Component. A storable action is a server action whose response is stored in the client cache so that subsequent requests for the same server method with the same set of arguments can be accessed from that cache.
To make an action storable, you simply call its setStorable() function. For example:
var action = component.get("c.getItems");
action.setStorable();
action.setCallback(this, function(response) {
    // handle response
};
$A.enqueueAction(action);
  • Expiration age: maximum age of the cached response. The cached response is discarded if it is older than the expiration age. In Lightning Experience, the expiration age is currently set to 900 seconds. This value is subject to change, and you can’t change it yourself.
  • Refresh age: maximum age for the cached response to be considered “fresh.” If the cached response is older than the refresh age (and younger than the expiration age), it is provided to the client, but the framework also invokes the server method in the background to refresh the cache. If the new response is different from the cached response, the action callback function is called a second time. In Lightning Experience, the refresh age is currently set to 30 seconds. Like the expiration age, this value is subject to change, and can’t be changed.
Lightning Components Best Practices: Caching Data with Storable Actions - Salesforce Developers Blog
Lightning DATA service in LWC :
  • OOB Edit and View of single record with in salesforce page.
  • obey Security sharing model
  • Effective caching of client data.
The easiest way to work with single records in Lightning web components is to use the lightning-record-*-form components. These base components use Lightning Data Service behind the scenes and inherit its caching and synchronization capabilities. Each base component gives you different features and levels of customization.
Here’s an example that uses lightning-record-form to create accounts.
accountCreator.html

<template>
    <lightning-card>
        <lightning-record-form
            object-api-name={objectApiName}
            fields={fields}
            onsuccess={handleSuccess}>
        </lightning-record-form>
    </lightning-card>
</template>
accountCreator.js

import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import REVENUE_FIELD from '@salesforce/schema/Account.AnnualRevenue';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
export default class AccountCreator extends LightningElement {
    objectApiName = ACCOUNT_OBJECT;
    fields = [NAME_FIELD, REVENUE_FIELD, INDUSTRY_FIELD];
    handleSuccess(event) {
        const toastEvent = new ShowToastEvent({
            title: "Account created",
            message: "Record ID: " + event.detail.id,
            variant: "success"
        });
        this.dispatchEvent(toastEvent);
    }
}
accountCreator.js-meta.xml

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


Comments

Popular posts from this blog

LearnSalesforce

LWC Interview Questions Part-1

Lightning Web Component