0% found this document useful (0 votes)
44 views14 pages

LWC Quetions and Ans

The document outlines key differences between JavaScript variable declarations (var, let, const), types of decorators in Lightning Web Components (LWC), lifecycle hooks, promises, and asynchronous programming techniques. It discusses parent-child communication, Lightning Data Service, Locker Service, and methods for calling Apex from LWC. Additionally, it highlights the advantages of LWC over Aura components and the importance of using async/await for cleaner asynchronous code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views14 pages

LWC Quetions and Ans

The document outlines key differences between JavaScript variable declarations (var, let, const), types of decorators in Lightning Web Components (LWC), lifecycle hooks, promises, and asynchronous programming techniques. It discusses parent-child communication, Lightning Data Service, Locker Service, and methods for calling Apex from LWC. Additionally, it highlights the advantages of LWC over Aura components and the importance of using async/await for cleaner asynchronous code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Difference Between Let, Var and Const

Var:-
 It can be declared without initialization.
 It is oldest keyword to declare variable,
 Var key word is goble, can access any where in the program(ex:-var a=10;) If we
declare Var variable out side of the function, we can access every where in the program.
 If variable declared inside of the function, user tries to access out side of the function it
will trough an error
 User can redeclare and update the Var Variable.
 The scope of a var variable is functional scope.
Let:- It can be declared without initialization. It is improved version of Var key word (let a=10;)
 Let Variable is only blocked scope
 Let variable can’t accessed outside of the particular function block.
 It can be updated but cannot be re-declared into the scope.
Const:- It can not be declared without initialization. Its updated version of let key word, Cannot
update the variable once declare it.
 The scope of a const variable is block scope.
 It cannot be updated or re-declared into the scope.

---------------------------------------------------------
Type of Decorators in Lightning Web Component
There are three type of Decorators in Lightning web components.

1. Api
2. Track
3. Wire
Let see them in details.

1. @api
To expose a public property or a public method, decorate with @api. Public properties are
reactive, also known as public reactive properties since if a value of property changes then
component is re-rendered

 Public properties define API of a component whereas public methods are part of a
component’s API
 A Component is re-rendered when the value of a referenced public property is modified
or changed
 To pass data from parent component to child component, @api decorator in the child
component exposes a property by making it public so that parent component can update
it
 @api properties can be exposed in an App builder
2. @track
 To expose a private property or a private method, declare with @track. Also known as
Private reactive properties
 To track a private property and to re-render component when that property changes, use
@track decorator (Available only for the component where it is declared)
 Fields which are using @track decorator that contains an object or an array, tells the
framework to observe changes to the properties of an object or elements of an array
 After Salesforce Spring ’20, all the fields in a Lightning Web Component are reactive. If
a field is used in a template & value changes, the component re-renders and displays a
new value by default

3. @wire
 Reactive wire service is utilized in Lightning Web Components to read the Salesforce
data from apex class into Lightning web components
 Component is re-rendered when wire service provisions the data from apex class. The
output from apex method is set to a property

---------------------------------------------------------
Lifecycle Hooks: -
Life cycle Hook is nothing but callback methods. Call back is passing a function into another
function as parameter or function as an argument to the function is calledback.
In life cycle hooks callback function will be there, within that call back function there are
methods, those methods are triggered at specific phase of component lifecycle called lifecycle
hook.

constructor()
Called when the component is created. This hook flows from parent to child, which means that
it fires in the parent first. You can’t access child elements because they don’t exist yet.

connectedCallback()
Called when the element is inserted into a dom. This hook flows from parent to child. You can’t
access child elements because they don’t exist yet.

renderedCallback()
Called after every render of the component. This lifecycle hook is specific to Lightning Web
Components, it isn’t from the HTML custom elements specification. This hook flows from
child to parent.

render()
Call this method to update the UI. It may be called before or after connectedCallback().

disconnectedCallback()
Called when the element is removed from a document. This hook flows from parent to child.
errorCallback(error, stack)
Called when a descendant component throws an error. The error argument is a JavaScript native
error object, and the stack argument is a string. This lifecycle hook is specific to Lightning Web
Components, it isn’t from the HTML custom elements specification.

---------------------------------------------------------
Promiss and Promiss-All
Promises: -
In LWC we call methods Asynchronous. So we don’t have much control in order of execution
if we have multiple methods.
Prior to promises events, callback functions were used but they had limited functionalities and
created unmanageable code.
Promises are the ideal choice for handling asynchronous operations in the simplest manner.
They can handle multiple asynchronous operations easily and provide better error handling
than callbacks and events. They also contain built-in mechanisms to chain one call after the
other.

Benefits of Promises
 Improves Code Readability.
 Better handling of asynchronous operations.
 A better flow of control definition in asynchronous logic.
 Error Handling is better than legacy callback.
A Promise has four states:
 fulfilled: Action related to the promise succeeded
 rejected: Action related to the promise failed
 pending: Promise is still pending i.e not fulfilled or rejected yet
 settled: Promise has fulfilled or rejected

Promises.All: -
Promise. all is a utility function that allows you to run multiple promises in parallel and handle
their responses together. It takes an array of promises as an argument and returns a new promise
that is resolved when all the promises in the array are resolved

---------------------------------------------------------
CallBack Hell: - callback hell (also known as "pyramid of doom") refers to the situation
where multiple nested callbacks are used, making the code difficult to read and maintain. This
happens when you have to execute a series of asynchronous operations, where the result of one
operation is used as input for the next operation, and so on.
example, we have four asynchronous operations (asyncOperation1, asyncOperation2,
asyncOperation3, and asyncOperation4) that are executed in sequence. Each operation requires
the result of the previous operation, so they are nested within callbacks. As more operations are
added, the nesting gets deeper, making the code harder to read and understand.
To avoid callback hell, you can use techniques like Promises, async/await, or function chaining.
Here's an example of how to use Promises to execute the same sequence of asynchronous
operations:

---------------------------------------------------------
Difference Between Aura and LWC

Why LWC over Aura ?


 The major difference between Aura and LWC, Aura’s inability to modify components
using standard UI elements. Modern businesses needed user experiences that were
tailored to them.
 To build contemporary, massive organizations, it was not possible to write client-side
technologies like modules, classes, decorations, or promises.
 Continuous UI changes required optimal rendering, although Lightning Components did
not have this issue.
 With LWC, you just need to write a few lines of code, and the LWC compiler will
translate it and add the required boilerplate code to make it into a web component.
 By boosting the time developers spend on more crucial application logic or UX
concerns and decreasing the time spent on business value, this helps your team be more
productive.
 The UI of LWC Components is optional and they are scalable, reusable, and
customisable. In any part of the application, these service components can be used.
Optimized, well-written code is beneficial.
 Developers working with Lightning Web Components simply need to understand how
to use the Lightning Web Component framer. They don’t need to learn other
frameworks or Java Script separately, as in the Aura programming model.
 LWC has built-in safety features. In addition, it has limited event scope and greater
CSS, script, and DOM isolation, giving applications better security and cross-browser
compatibility.
 LWC enables the use of complete encapsulation.

---------------------------------------------------------
Event.StopPropagation and Event.PreventDefault:-
 Event.stopPropagation(): - The stopPropagation() method of the Event
interface prevents further propagation of the current event in the capturing and bubbling
phases.
 Event.preventDefault(): - method cancels the event if it is cancelable, meaning that the
default action that belongs to the event will not occur.

---------------------------------------------------------
Parent to Child Communication: -
Parent to Child communication happens between two components when the parent
component contains the child component tag in its HTML file and passes data to the child
component. To pass data to the child component, we need to define a variable with @api
decorator in the child component to be public and accessed from the parent component.
Note: @api decorator used to define public property, which is reactive.
An Example for Better Understanding
Here we defined a variable getValueFromParent using the @api decorator in child and used
it in the HTML template to display its value in the child component.
Now moving towards the parent component, declare one variable in the parent
component to pass it to the child component. Here we created a value variable and
assigned a string literal to it. To pass the value to the child component, add the child
component’s tag to the parent HTML template and assign the value to the child’s
property as an attribute.

Child-to-Parent Communication: -
As we have seen, passing a public property from a parent and receiving it in the child is the
easiest way to achieve Parent to Child communication. In the case of Child to Parent
communication, it is a bit more complicated. From the child component, we will pass the
value to the parent component using CustomEvent.
Note: The CustomEvent constructor has one required parameter: a string, which refers to the
event type.
In this example, when the user enters something in the lightning input field, the component
creates and dispatches the CustomEvent called getsearchvalue event. The event includes the
data in detail property.
The parent component listens for the getsearchvalue event in the ongetsearchvalue attribute
and handles it in the handleSearchValue event handler. In handleSearchValue, we are
assigning the value from the event. detail to searchValue variable.
In this way, we can perform Parent-Child communication effectively. Remember, in the
above example, the components are related, but when the components are not related
through the parent-child relationship, we can perform communication using the pubsub
model and lightning message service (LMS).

---------------------------------------------------------
What is Lightning Data Service?
Lightning Data Service is a centralized data caching mechanism which is utilized to perform
create, read, update or delete on a record without having a server side apex call in Lightning
web components.
If a Lightning Page is composed of multiple components which displays information related
to the same record, it means that the record loads only once in Lightning Data Service are
cached and shared across components. There is a significant performance improvement in
the components because a record loads only once no matter even if many components use it.

Advantages of Lightning Data Service


 No server side apex call as the record is cached & retrieved from client-side cache of
record data that has been loaded via a wire adapter, thus eliminating multiple calls to the
server
 Lightning Data Service is built on top of User Interface API, the responses respect
CRUD access, field-level security, and sharing settings pertaining to a User.
 Invalidates cache entries for dependent Salesforce data and metadata changes.
Whenever changes happen to the same record or metadata, LDS always has the latest
copy of the record in the cache
 LWD always maintains consistent data across multiple components. If several
components use Lightning Data Service to work with the same record, and one of the
components updates the record, the other components will automatically reflect the
update.
When the record is loaded for the first time in a component, Lightning Data Service maintains
that data in the client-side cache. The data in the cache has a specific lifetime defined. If any
request is made to the data within that lifetime then the data is served from cache else it resets
the cache data lifetime. If the data changes in the component, then the data is re-requested
before its cache lifetime ends.

Below are the 3 base lightning components build on Lightning Data Service:
 lightning-record-form: A form with standard lightning UI to create, view or edit a
record
 lightning-record-edit-form: A form to create record with specified fields or update
fields in an existing record
 lightning-record-view-form: A form to display specific fields data of a record in read-
only mode

---------------------------------------------------------
Locker Service
Locker Service is a powerful security architecture for Lightning components. Locker
Service enhances security by isolating Lightning components that belong to one
namespace from components in a different namespace. Locker Service also promotes
best practices that improve the supportability of your code by only allowing access to
supported APIs and eliminating access to non-published framework internals.

Prevent:
 Components from causing XSS and similar security issues
 Components from reading other component’s rendered data without any
restrictions
 Components from calling undocumented/private APIs
Enable:
 Cool new features like client-side API versioning similar to REST API
versioning
 Faster security review
 Better and more secure JS development practices
 Running 3rd party JS frameworks like React, Angular and so on
 Easily adding or removing new security features and policies

---------------------------------------------------------

Asynchronous Programming in LWC


 Asynchronous operations involve tasks that don't complete immediately, such as
fetching data from a server or interacting with external APIs.
 LWC provides mechanisms to handle these operations effectively.

Async/Await Syntax
 Introduced in ES2017 (ECMAScript 2017), this syntax offers a cleaner way to
write asynchronous code.
 async keyword: Declares an asynchronous function, which inherently returns a
promise.
 await keyword: Used within an asynchronous function to pause execution until
a promise resolves or rejects.
Benefits of Async/Await
 Improved Readability: Makes asynchronous code look more synchronous,
enhancing code clarity.
 Error Handling: await automatically throws any errors returned by the awaited
promise, simplifying error handling.
 Reduced Callback Hell: Avoids nested callback chains, making code easier to
maintain.

Example: Fetching Data with Async/Await


JavaScript
import { LightningElement, api } from 'lwc';

export default class MyLwc extends LightningElement {


@api recordId;
data;
error;

async fetchData() {
try {
const response = await fetch(`/your/api/endpoint/${this.recordId}`);
this.data = await response.json();
} catch (error) {
this.error = error;
}
}

renderedCallback() {
if (this.recordId) {
this.fetchData();
}
}
}
Use code with caution.
content_copy

Explanation:
1. The fetchData function is declared as async.
2. await fetch pauses execution until the fetch operation completes.
3. await response.json() waits for the response to be parsed as JSON.
4. If successful, data is assigned the parsed data.
5. In case of errors, the catch block handles them, and error is set.
6. renderedCallback checks if recordId exists and calls fetchData if so.

Key Points
 await can only be used within async functions.
 Always handle potential errors using try...catch blocks.
 Consider using @lwc/recommendation for code recommendations and best
practices.
By effectively using Async/Await in your LWC components, you can write cleaner, more
maintainable asynchronous code that enhances the user experience of your Salesforce
applications.

---------------------------------------------------------
Call Apex method from LWC
After importing the apex class method you can call the apex methods as functions into the
component by calling either via the wire service or imperatively. To call an Apex method, a
Lightning web component can:

 Wire a property
 Wire a function
 Call a method imperatively

To expose an Apex method to a Lightning web component, the method must be static and either
global or public. Annotate the method with @AuraEnabled

Wire Property with Apex


As per the wire method writing rules, first we have to import method (apexMethod) from the
Apex Class.

import apexMethod from '@salesforce/apex/Namespace.Classname.apexMethod';

Then, property is wired to apexMethod in below format :-

@wire(apexMethod, { apexMethodParams }) propertyOrFunction;

Now we can get the data using {property.data} & error using {property.error} in html file.

Use Case : Business want to create one page to search all account records base on account
name.

Let’s see how we can create one Lightning web component to achieve this requirement

First we need to create one apex class with @AuraEnabled

public with sharing class AccountService {


@AuraEnabled(cacheable=true)
public static List<Account> getAccounts(String strAccountName) {
String strKey = '%'+strAccountName+'%';
List<Account> accList = [SELECT Id,Name,AccountNumber FROM Account WHERE name
like :strKey ];
return accList;
}
}

Then create one Lightning Web component “searchAccount” and then modify the
“searchAccount.js” file to import the apex method “getAccounts” from apex class.

import { LightningElement, wire, track } from 'lwc';


import getAccounts from'@salesforce/apex/AccountService.getAccounts';
export default class SearchAccount extends LightningElement {
@track searchKey;
@wire (getAccounts,{strAccountName: '$searchKey'}) accounts;
handleKeyChange(event){
this.searchKey = event.target.value;
}
}

During passing of the parameters, we need to put ‘$’ sign before the property.

Now we can get the data using {accounts.data} & error using {accounts.error} in html file.

<template>
<lightning-card title="Search Account" icon-name="custom:custom57">
<div class="slds-m-around_medium">
<lightning-input type="search" onchange={handleKeyChange}
class="slds-m-bottom_small" label="Search"></lightning-input>

<template if:true={accounts.data}>
<template for:each={accounts.data} for:item="acc">
<lightning-layout vertical-align="center"
key={acc.id}>
<li>
{acc.Name}
{acc.AccountNumber}
</li>
</lightning-layout>
</template>
</template>
</div>
</lightning-card>
</template>

to use same LWC component on Home page modify “searchAccount.js-meta.xml” file like
below.

<?xml version="1.0" encoding="UTF-8"?>


<LightningComponentBundlexmlns="http://soap.sforce.com/2006/04/metadata"
fqn="SearchAccount">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<targets>

<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Wire Function with Apex


There is another way to use wire as function. Let’s see how we can modify the above LWC
component to use as Wire Function.

No changes required in Apex class and searchAccount.js-meta.xml file. We need to modify


our js file. We need to defined two private reactive properties such as accounts and error. Then
we need to set these two properties into the wired function named wiredAccounts.

import { LightningElement, wire, track } from 'lwc';


import getAccounts from '@salesforce/apex/AccountService.getAccounts';
export default class SearchAccount extends LightningElement {
@track searchKey;
@track accounts;
@track error;

@wire (getAccounts,{strAccountName: '$searchKey'})


wiredAccounts({data, error}){
if(data) {
this.accounts =data;
this.error = undefined;
}else {
this.accounts =undefined;
this.error = error;
}
}

handleKeyChange(event){
this.searchKey = event.target.value;
}
}

Now, we will get the Account record details using only {accounts} instead of {accounts.data}
applied for wire method to property mechanism in HTML file.

<template>
<lightning-card title="Search Account Wired Function"
iconname="custom:custom57">

<div class="slds-m-around_medium">
<lightning-input type="search" onchange={handleKeyChange}
class="slds-m-bottom_small" label="Search"></lightning-input>
<template if:true={accounts}>
<template for:each={accounts} for:item="acc">
<lightning-layout vertical-align="center"
key={acc.id}>
<li>
{acc.Name}
{acc.AccountNumber}
</li>
</lightning-layout>
</template>
</template>
</div>
</lightning-card>
</template>

Imperative Method with Apex


Now we have a good understanding of using wire mechanism in Lightning Web Component.
Let’s talk about how to get salesforce data with imperative service. Here is example of LWC
call Apex method with parameters imperatively.

NOTE :- For Imperative method we dont need to mark the apex method as
cacheabe=true.

Let’s modify the above example into the imperative mechanism. We need to modify our js file
like below

import { LightningElement, track } from 'lwc';


importgetAccounts from '@salesforce/apex/AccountService.getAccounts';
export default class SearchAccount extends LightningElement {
@track accounts;
@track error;
handleKeyChange(event){
constsearchKey = event.target.value;
getAccounts({ strAccountName: searchKey })
.then(result => {
this.accounts = result;
this.error = undefined;
})
.catch(error => {
this.error = error;
this.accounts = undefined;
})
}
}

Wire Vs Imperative
Always prefer to use @wire over imperative Apex method invocation. @wire fits nicely in the
overall Lightning Web Component reactive architecture as per lightning web component best
practices.

However, we have some use cases where we require to use imperative Apex. For example,
when you need to invoke an Apex method without responsive parameters in response to a
specific event, like a button click event to get record.

Now we know @wire is recommended way by Salesforce but we have two way to implements
@wire an apex method

 Wire an Apex method as property.


 Wire an Apex Method as function.

Now, which one is recommended? Prefer way is us @wire as property.

Here is some consideration

 First, import the Apex method into the JS


 If it is wired, make sure cacheable=trued decorator is set
 Parameters are passed as an object
 For simple results: wire to a property
 For some processing: wire to a function
 For controlling when to call: imperative

---------------------------------------------------------

You might also like