[go: up one dir, main page]

0% found this document useful (0 votes)
90 views17 pages

LWC Concepts

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 17

LWC INTERVIEW QUESTIONS

1. What is LWC?
 It is UI Framework that salesforce developers use to create customized
Pages.
 It uses Standardized JavaScript Framework, HTML, CSS Without a Third-
Party framework.
 These components are reusable ‘building blocks’ that Salesforce Admins can
deploy for a variety of use cases.
2. Lifecycle Hooks
 Constructor
 ConnectedCallBack
 render
 RenderedcallBack
 DisconnectedCallback
3. Wire Method Syntax
@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;
}
}

Q: Why do we use '$' sign in getRecord wired function


 To tell the wire method that it should listen for changes to this property and
perform some server call in response.
 Without the $, the string is just a normal string, and if you just
use this.variableName, you only get one shot from the wire method (because it ends
up looking like a string/number/whatever).
 We need this special symbol to make wire properties reactive.

4. What is the file structure of Lightning Web Components


1. myComponent folder
myComponent.html
myComponent.js
myComponent.js-meta.xml
myComponent.css
myComponent.svg

The folder and its files must follow these naming rules.

 Can’t contain a hyphen (dash)


 Must begin with a lowercase letter.
 Can’t include whitespace.
 contain only alphanumeric or underscore characters.
 Can’t end with an underscore.
 Must be unique in the namespace.
 Can’t contain two consecutive underscores.

5. How can you display HTML Components Conditionally


 To render HTML conditionally, add the if: true|false directive to a
nested <template> tag that encloses the conditional content.
6. How can we bind data in LWC?
 In the template, surround the property with curly braces, {property}.
 To compute a value for the property, use a JavaScript getter in the JavaScript
class, get property () {}.

7. How can we pass data from HTML to JS controller?

 We can use the on-change attribute to listen for a change to its value. When the
value changes, the handle Change function in the JavaScript file executes.

 <lightning-input name='firstName' label="First Name"


onchange={handleChange}></lightning-input>

 <lightning-input name='lastName' label="Last Name"


onchange={handleChange}></lightning-input>

 In Controller

 handleChange(event) { const field = event.target.name; if (field === 'firstName')


{ this.firstName = event.target.value; } else if (field === 'lastName') { this.lastName =
event.target.value; } }

8. Can we display multiple templates?


 Yes, we can, we can import multiple HTML templates and write business
logic that renders them conditionally.

 Create multiple HTML files in the component bundle. Import them all and
add a condition in the render () method to return the correct template
depending on the component’s state.

 // MultipleTemplates.js

 import { LightningElement } from 'lwc';

 import templateOne from './templateOne.html';

 import templateTwo from './templateTwo.html'; export default class


MultipleTemplates extends LightningElement {

 templateOne = true;

 render() { return this.templateOne ? templateOne : templateTwo; }


switchTemplate(){ this.templateOne = this.templateOne === true ? false :
true; } }

Communication Between LWC Components


 The term "communication" refers to the exchange of information between two or
more components.
 There are two possibilities. Both components are related to one another through a
relation, such as a Parent-Child Relationship, or they are unconnected to one
another.
 From Parent-Child we have two types
1. Parent-Child Communication
2. Child-Parent Communication

Parent To Child Communication


 Parent to Child communication occurs when a parent component includes the child
component element in its HTML file and transmits data to the child component.
 To provide data to the child component, we must create a public variable in the child
component that can be accessed from the parent component using the @api
decorator.
 The @api decorator is used to establish reactive public properties .
9. Life Cycle of Component

A. Constructor: Called when the component is created.


B. Connectedcallback: Called when the element is inserted into a document. This
hook flows from parent to child.
C. 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. Ie its not part of HTMLElement
rather defined in LightningElement.
D. Disconnectedcallback : Called when the element is removed from a document. This
hook flows from parent to child.
E. Errorcallback: 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.

Note:
1. Do not use renderedCallback() to change the state of a component, such as loading
values or setting properties. Use getters and setters instead.
2. Don’t update a wire adapter configuration object property in renderedCallback(), as
it can result in an infinite loop.
3. Don’t update a reactive property or field in renderedCallback(), as it can result in an
infinite loop.

Q. How can I reference record ID of page in my component which is fired


from quick action.
1. There are two types of quick actions in LWC :
Screen actions : Normal action which open a modal
Headless actions : Which dont have any html file rather just logic written in js ie no
modal window will come up
2. In case of screen actions we will be able to get recordID by just defining recordID as
public property in the component.
For headless action you have to define @api invoke method which is auto called and
recordID will be set after this function is called.
Types of LWC Actions

1. When it comes to record page Lightning Web Components, there are two types:
A. Screen Quick Actions and
B. Headless Quick Actions.
2. Screen Quick Action
A. These allow users to carry out updates via a modal window, like filling in a form
to create or edit a new record.
3. Headless Quick Action
A. These allow you to carry out an action without the need to display, such as
navigating to another page or dispatching an event.
How do I know which I should use?

10.What is a promise in async transactions? What are it different


stages.
Promise provides a way to handle the response of an asynchronous operation,
whether it is successful or not.
1. A promise is an object that represents a value that may not be available yet.
The promise object has two main methods: then and catch.
2. The then method is called when the promise is resolved (i.e. the
asynchronous operation is successful), and it receives the value of the
promise as an argument.
3. The catch method is called when the promise is rejected (i.e. the
asynchronous operation failed), and it receives the error as an argument.

Promise.race

1. It is a utility function that allows you to run multiple promises in parallel and
handle the response of the first promise that is resolved or rejected.
2. It takes an array of promises as an argument and returns a new promise that
is resolved or rejected as soon as one of the promises in the array is resolved
or rejected.
10.What is Async and Await?

1. Async/await is essentially a way to write asynchronous code that looks and


behaves more like synchronous code.
2. Async/await is built on top of promises, which are used to handle
asynchronous operations in JavaScript.
3. The async keyword is used to define an asynchronous function, which
returns a promise.
4. Within this function, you can use the await keyword to pause the
execution of the function until a promise is resolved or rejected.
5. This makes your code look more like synchronous code, as the execution is
blocked until the promise resolves.

How to use Async and Await in Lightning Web Components

import { LightningElement } from 'lwc';


import fetchData from './fetchData';
export default class MyComponent extends LightningElement {
async connectedCallback() {
const response = await fetchData(‘api/data’);
const data = await response.json();
console.log(data);
}
}

Common Use Cases for Async and Await

As you can see, the use of async and await is not limited to just making API calls. In fact,
they're very useful when you want to perform an action that takes a long time. For
example:
 Making HTTP requests
 Waiting for an asynchronous action to finish
 Processing multiple promises in parallel

Error Handling with Async and Await

As you've seen, async functions return promises. If an exception is thrown in an async


function, the promise it returns will be rejected with that exception. This can be handled by
catching errors with try/catch blocks as usual:
try {
await someAsyncFunction(arg1);
// do something else here...
} catch(e) {
// handle error here...
}
Difference between Async/Await and Promise

 An async function always returns a Promise, and within an async function, you can
use await to pause the execution until a Promise is resolved.
 While both approaches achieve the same result, async/await is often considered
more readable and easier to work with, especially when dealing with complex
asynchronous flows.

11.Difference between Pub-Sub and LMS

The Pub-Sub pattern in LWC was initially used for event communication
between unrelated components on the same Lightning page. LMS allows
communication between components across different pages and
between Visualforce pages and various types of Lightning components,
including LWCs and Aura components.

Platform Event with Lightning Web Components

Introduction to Platform Events


1. It allows applications to communicate with each other in a loosely coupled, event-
driven architecture.
2. Using platform events applications can publish events when something of interest
happens, and other applications can subscribe to those events to take action.
3. It works with Apex, Lightning components and Visualforce.
4. They are like custom objects in that they can be defined with fields and triggers.
5. They are optimized for high-volume event delivery and are designed to be
consumed by external applications as well.
Call Apex method from LWC
1. LWC. Lightning web components can import methods from Apex classes into the
JavaScript classes using ES6 import.

Syntax: import apexmethod from


‘@salesforce/apex/namespace.classname.methodname’;
2. 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.
1. Wire Property with Apex
 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.
Wire Function with Apex

Imperative Method with Apex

Note: - For Imperative method we don’t need to mark the apex method as cacheabe=true.
Usage: 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.

Differences between the wire and imperative calls:

1. One of the main differences between the wire and imperative calls is how data is
retrieved and updated. Wire calls provide real-time updates to the data in the
LWC, while imperative calls require the developer to explicitly retrieve and
update the data.
2. Another difference between the two methods is how the data is stored. With wire
calls, the data is stored in a reactive variable that updates automatically
whenever the data on the server-side changes. With imperative calls, the data is
stored in a regular variable and needs to be updated manually.

Pros of using wired apex method call:

 Automatic data refreshing: Wired apex method calls provide automatic data
refreshing, meaning that any changes made to the data are automatically reflected in
the UI without requiring any additional code.
 No need for error handling: Since the wired apex method calls handle errors
automatically, you don’t need to write any additional code for error handling.
 Better performance: Wired apex method calls use a reactive programming model
and optimize the data transfer between the server and client, resulting in better
performance.
Cons of using wired apex method call:

 Limited data manipulation: Wired apex method calls are read-only and do not
allow for any data manipulation or updates.
 Limited control over the data: Wired apex method calls automatically fetch and
cache data, which can result in less control over the data and its behavior.
 Limited support for complex queries: Wired apex method calls only support
simple queries and may not be suitable for more complex queries that require
additional logic.

Pros of using imperative apex method call:

 Full control over data: Imperative apex method calls allow full control over data
and its behavior, allowing for DML operations such as updates, inserts, and deletes
as needed.
 Support for complex queries: Imperative apex method calls allow for complex
queries and additional logic, making them suitable for more complex use cases.
 Better debugging: Since the imperative apex method calls to provide more control
over the data, they also allow for easier debugging of issues.

Cons of using imperative apex method call:

 More error-prone: Imperative apex method calls require more error handling code
since they do not handle errors automatically as wired apex method calls.
 Manual data refreshing: Since imperative apex method calls do not provide
automatic data refreshing, you need to write additional code to manually refresh the
data.
 Lower performance: Imperative apex method calls require more code and data
transfer between the server and client, resulting in potentially lower performance
compared to wired apex method calls.

Best Practices:

1) Always Cache Data.


2) Use Conditional Rendering.
3) Use Pagination with lists.
4) Use Base Lightning Web Components
5) Use SLDS Icons and Styling

LWC querySelector usage

 In LWC this.template.querySelector is used to select an element, Here element can


be div, span, input or any tag inside lwc component.
 In querySelector we use classname to uniquely identify a particular element and if
there are more than one element, we use querySelectorAll and run a loop on it.
 But there is more to querySelector, we can uniquely identify based on data-id, data-name,
if there are more than one element.

Errors in LWC
1. If you write wire method inside function, leading decorators must be attached to
class which means decorators like wire, track, Api can be directly under class only
not inside any other function.

How to fetch Picklist values in Lightning Web Components(lwc)


 use getPicklistValues wire adapter to fetch picklist values for a specified field.
 Parameters:
1. recordTypeId—(Required) The ID of the record type. Use the Object Info
defaultRecordTypeId property, which is returned from getObjectInfo or
getRecordUi.
2. fieldApiName—(Required) The API name of the picklist field on a supported
object.
3. propertyOrFunction—
i. A private property or function that receives the stream of
data from the wire service.
ii. If a property is decorated with @wire, the results are
returned to the property’s data property or error property.
iii. If a function is decorated with @wire, the results are
returned in an object with a data property and an error
property.
What is Lightning Data Service?
1. 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.
2. 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.
3. 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
1. 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.
2. 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.
3. 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.
4. 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.
5. When the record is loaded for the first time in a component, Lightning Data Service
maintains that data in the client-side cache.
6. The data in the cache has a specific lifetime defined.
7. 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.
8. 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:
1. lightning-record-form: A form with standard lightning UI to create, view or edit a
record.
2. lightning-record-edit-form: A form to create record with specified fields or update
fields in an existing record.
3. lightning-record-view-form: A form to display specific fields data of a record in
read-only mode.

lightningRecordFormDemo.html

Reference Links
1. https://www.codingninjas.com/codestudio/library/difference-between-var-
let-and-const-in-js

2. https://www.apexhours.com/lightning-message-service-lms-
messagechannel/
3. https://salesforce.stackexchange.com/questions/383706/update-records-in-
lwc-using-apex
4. https://salesforcescool.blogspot.com/2021/11/refresh-datatable-after-edit-
record-in.html
5. https://www.sfdcblogs.com/post/how-to-fetch-inputs-in-lightning-web-
components
6. https://dineshyadav.com/salesforce-lightning-message-service-explained/
7. https://www.crsinfosolutions.com/enhancing-performance-with-dom-
manipulation-in-lightning-web-components/
8. https://www.crsinfosolutions.com/understanding-lifecycle-hooks-in-
lightning-web-components/
9. https://jayakrishnasfdc.wordpress.com/2020/12/06/wire-service-in-
lightning-web-component-lwc/

You might also like