LWC 2024
LWC 2024
connectedCallback(){
console.log('In connectedCallback');
}
}
render()
• Hook that overrides the standard rendering functionality.
• Gets invoked after connectedCallback() and must return a valid
HTML template.
• It can fire more than once.
• It flows from parent to child.
import { LightningElement } from 'lwc';
export default class App extends LightningElement {
render(){
console.log('In render');
}
}
renderedCallback()
• Fires when a component rendering is done.
• It can fire more than once.
• It flows from child to parent.
The renderedCallback() is unique to Lightning Web Components.
import { LightningElement } from 'lwc';
export default class App extends LightningElement {
renderedCallback(){
console.log('In renderedCallback');
}
}
disconnectedCallback()
• Fires when a component is removed from the DOM.
• It can fire more than once.
• It flows from parent to child.
• The equivalent in aura was the unrender() methods of the custom
renderer file.
When this component removed form DOM, it will fire disconnectedCallback
and clear array.
import { LightningElement } from 'lwc';
export default class App extends LightningElement
{
disconnectedCallback(){
console.log('In disconnectedCallback');
}
}
errorCallback(error, stack)
Captures errors that may happen in all the descendant components
lifecycle hooks.
errorCallback(error, stack) {
alert(error);
}
2.Why we Use of lifecycle hooks ?
Dynamic rendering of components: we can use the render() hook to
render different templates according to some conditions.
Component that is an error boundary for the descendent components
lifecycle hooks: we can use the errorCallback() to implement such
component.
17.What is LMS?
LMS is defined as the standard publish-subscribe library that enables
communication with DOM across the components be it Visualforce Pages,
Aura components, and Lightning Web Components (LWC) all can use it to
publish message and listen to messages published by others.
18.Do we have application events in LWC?
Ans: We dont have application event as such in LWC like Aura rather we
have LMS in LWC to communicate between components which are not part
of same hierarchy.
19.How can we navigate user from LWC component to record detail
page?
We can do it using NavigationMixin service
20.Can I get current user ID in LWC without apex?
Yes we can get current user ID without apex by simply importing
import Id from ‘@salesforce/user/Id’
21.Can i call function annotated with @AuraEnabled(cacheable= true)
imperatively ?
Ans: Yes
22.Can we do DML in method annotated with
@AuraEnabled(cacheable= true)?
Ans: No we can’t do DML inside any method annotated with cacheable =
true , you will receive an error as DMLLimit Exception.
23.How to refresh cache when calling method imperatively?
We have to use getRecordNotifyChange(RecordIds) which refreshes the
LDS cache providing you the latest data this will work only if cacheable =
true was there. Otherwise we will have to call the function again from our js
to get the latest data.
24.When do we face error of “Cant assign to Read only property” in
LWC?
This error occurs when you are trying to make changes to a property which
is marked as @api , ideally you should clone the value then make the
changes to it.
25.How do you handle errors and exceptions in LWC?
Error handling in LWC can be done using try-catch blocks or by leveraging
the onError lifecycle hook. You can catch exceptions and display
appropriate error messages to the user, ensuring a smooth user
experience.
<template>
try {
// Code that may throw an exception
} catch (error) {
// Handle the error and display an error message
}
</template>
26.How do you make an HTTP callout from a Lightning Web
Component?
You can use the fetch API to make HTTP callouts in LWC . Import the fetch
method and use it to send requests to external services.
27.What is the purpose of the lightning-record-edit-form component in
LWC?
lightning-record-edit-form is used to create, view, or edit a record’s fields
using the Salesforce Lightning Data Service.
28.How can you communicate between sibling components in LWC?
You can use custom events and properties defined in a common parent
component to facilitate communication between sibling components.
29.How can we track the database changes in the Lightning web
component and refresh UI on data updates?
If we need to track the changes done by Lightning Data Service then we
can use the getRecordChangeNotifiy() function from the LDS.
30. Suppose you have written a LWC which has the @wire decorator
to get the data from apex. But you are unable to get the data from the
server. What could be one of the reason?
check whether you have used cacheable=true along with @AuraEnabled
annotation in the apex method.
32.Can I call function annotated with @AuraEnabled(cacheable= true)
imperatively ?
Yes
33.How to ensure that your LWC respects FLS?
1. Use Standard Components Where Possible: Use Lightning Data
Service components
like lightning-record-form, lightning-record-view-form, and lightning-record-
edit-form, respect FLS automatically. Whenever possible, use these
components to handle data input/display.
<lightning-record-view-form record-id={recordId} object-api-
name=”Account”>
<lightning-output-field field-name=”Name”></lightning-output-field>
<!– other fields –>
</lightning-record-view-form>
In this example, FLS is enforced for the “Name” field of the “Account”
object, and if a user doesn’t have permission to view the “Name” field, it
won’t be displayed.
2. Check FLS in Apex:
When writing Apex controllers that are called from your LWC, always check
FLS. Use the SecurityEnforced annotation.
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static Account getAccount(Id accountId) {
return [SELECT Id, Name FROM Account WHERE Id = :accountId
WITH SECURITY_ENFORCED];
}
}
The WITH SECURITY_ENFORCED clause ensures that the query
respects FLS, throwing an exception if the user lacks the necessary
permissions.
3. Use Schema Methods in Apex:
Utilize Schema methods in Apex to check if the current user has read,
create, or edit access to a field. This is more manual but allows for fine-
grained control.
public with sharing class SecurityCheck {
public static Boolean isFieldAccessible() {
return Schema.sObjectType.Account.fields.Name.isAccessible();
}
}
53. Give me a scenario where you will use Lightning Message Service
in LWC?
There is a parent component that has two child components. One child
component is responsible for displaying a list of items, while the other child
component is responsible for displaying the details of the selected item.
When the user selects an item from the list, the first child component can
send a message on a specific channel with the details of the selected item.
The second child component, which has subscribed to the same channel,
can receive the message and update its display with the new details.
54. Can you explain the role of the Salesforce Object Query Language
(SOQL) in LWC?
SOQL is a query language used in Lightning Web Components (LWC) to
retrieve data from the Salesforce database. The wire adapters and
imperative Apex calls in LWC provide developers with ways to make
server-side calls to retrieve data using SOQL.
55. Explain Bounded and Unbounded Expressions in LWC.
In LWC, expressions are used for dynamically displaying the data in the
template. There are two types different types of expressions in LWC:
• Bounded expressions are enclosed within double curly braces ({{
}}). They are used to display data values in the template that are
derived from the component's JavaScript class or HTML attributes.
• Let’s understand this through an example -
<template>
<p>Hello {{name}}, welcome to my website!</p>
<p>The result of adding 3 and 2 is {{addNumbers(3, 2)}}.</p>
</template>
• Unbounded expressions are enclosed within single curly braces ({
}). They are used to evaluate JavaScript expressions in the template
itself. Unbounded expressions can be used to assign values to HTML
attributes or to conditionally render HTML elements.
Let’s understand this also with an example -
<template>
<input type="text" value={inputValue}>
<template if:true={showMessage}>
<p>The message is: {message}</p>
</template>
</template>
56. How can you render multiple templates in LWC?
In LWC, we can display multiple templates conditionally based on the
component's state using the if:true directive.
Here's an example of how to display multiple templates in LWC:
<template>
<template if:true={showTemplate1}>
<p>This is template 1</p>
</template>
<template if:true={showTemplate2}>
<p>This is template 2</p>
</template>
</template>
57. How do you handle user input in LWC forms?
We can handle user input in forms using event handlers and data binding.
• Event Handlers: LWC provides some built-in event handlers that we
can use for handling user inputs, like - onClick, onChange,
onSubmit, etc. For example, Suppose we want to handle a button
click event, we can define an onClick event handler on the button
element like this:
• Data Binding: LWC has some data binding features inbuilt that help
in binding the value of an input element to a property in the
component state.
58. Explain in detail about @api and @track decorators in LWC.
In LWC, both @api and @track decorators are used to define properties in
a component, but they serve different purposes.
• The @api decorator is used to define a public property that can be
accessed by other components. This allows passing data between
components in a parent-child relationship, or between unrelated
components using the Lightning Message Service. Here's an
example of how we can use the @api decorator to define a public
property:
import { LightningElement, api } from 'lwc';
62. How do you use the Salesforce REST API in LWC? What are the
best practices for integrating with external systems?
To use the Salesforce REST API in LWC, we can use the built-in fetch
method or a third-party library like axios or jQuery.
63. Can you explain how to use the LWC component cache and why it
is important for performance?
When a user loads a page that contains LWC components, the browser
needs to download and render those components. This problem can be
solved using the LWC component cache.
This helps speed up this process by storing copies of the components in
the browser's cache.
So, in the case when the browser does not need to download the
components every time the user accesses the page. Instead of this, the
cached components can be quickly retrieved and displayed. This helps in
reducing page load time and improves the user experience.
To enable the LWC component cache, we need to use
the @wire decorator with the getRecord or getListUi wire adapters. These
adapters automatically cache the results of the wire call in the browser's
cache, which can help improve performance.
For custom logic or UI elements that need to respect FLS, you can use the
UserRecordAccess object in SOQL or Apex methods like isAccessible(),
isUpdateable(), and isCreateable() to check field-level permissions.
<template>
<lightning-record-view-form record-id={recordId} object-api-
name="Account">
<lightning-output-field field-name="Name"></lightning-output-field>
<lightning-output-field field-name="Industry"></lightning-output-field>
</lightning-record-view-form>
get industry() {
return getFieldValue(this.account.data, INDUSTRY_FIELD);
}
}
Here, getRecord is used to fetch the record data, and getFieldValue is used
to extract specific field values.You can decide exactly how to display the
data. For example, you can wrap the field values in custom HTML and
apply your own styles or formatting.
This approach gives you full control over the presentation and any
additional logic you want to apply to the data, such as conditional
rendering, formatting, or integrating with other data sources.
78. How To get records from two different objects and still maintain
Field-Level Security (FLS) in Lightning Web Components?
You can use either Lightning Data Service (LDS) components or @wire
adapters. Both approaches ensure that FLS is respected, meaning users
only see the fields they have permission to access.
Using Lightning Data Service (LDS) Components
With LDS, you can use separate lightning-record-view-form components for
each object. Each form will handle FLS and display only the fields that the
user is allowed to see.
Using @wire Adapters
Alternatively, you can use @wire adapters to fetch data from different
objects. You will need separate wire methods for each object. FLS is
automatically respected when using getRecord.
Choose the method that best fits your needs for control, customization, and
ease of use. LDS components are easier and more convenient for standard
form layouts, while @wire adapters offer more flexibility for custom logic
and data handling.
Using refreshApex
If you are using @wire in combination with imperative Apex calls, you can
use refreshApex. This function re-executes the @wire service, refreshing
the data.
// Re-fetches the data wired to wiredRecordResult
refreshApex(this.wiredRecordResult);
80. When and when not to Refresh Data in LDS?
Manual Data Changes Outside of Salesforce UI:
Let’s say, If data is changed outside the standard Salesforce UI, such as
through an external system integration, API call, or custom Apex operation,
and those changes need to be reflected immediately in your LWC.
Use methods like refreshApex to ensure the latest data is displayed.
Apex Class:
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts() {
return [SELECT Id, Name, Industry FROM Account];
}
}
JavaScript Controller:
import { LightningElement, track } from 'lwc';
import getAccounts from
'@salesforce/apex/AccountController.getAccounts';
connectedCallback() {
this.loadAccounts();
}
loadAccounts() {
getAccounts()
.then(result => {
this.accounts = result;
})
.catch(error => {
this.error = error;
});
}
}
// Cloning to modify
let clonedProperty = { ...this.parentProperty };
clonedProperty.someField = 'newValue';
processOrder(() => {
console.log('Order is processed');
});
90. What is Promise.all and how does it work?
Promise.all is a method that takes an array of promises and returns a
single promise that resolves when all the promises have resolved. It rejects
if any of the promises are rejected.
Promise.all is like waiting for all dishes in an order to be ready before
serving them to the customer, ensuring that everything is served together.
Promise.all([promise1, promise2]).then(results => {
console.log(results);
});
91. What is Shadow DOM in LWC?
Shadow DOM provides encapsulation for a component's styles and
markup, ensuring they do not interfere with the styles and markup of the
rest of the document.
Shadow DOM is like having a private dining area in a restaurant where the
decor and atmosphere (styles and markup) are different from the main
dining room, ensuring a unique experience that doesn't affect the rest of the
restaurant.
Code Snippet:
javascript
<template>
<p class="shadow-p">Styled independently</p>
</template>
<style>
.shadow-p {
color: red; /* Only affects this component */
}
</style>
94. What tools do you use for deployment in Salesforce, and how do
they integrate with LWC?
Tools like GitHub and Copado are used for version control and deployment.
In GitHub, developers pull the latest code, commit changes, and push
updates. Copado helps manage the deployment pipeline.
95. What are some best practices in LWC development?
1. Component Reusability: Write reusable components, such as
creating a separate component for displaying toast messages.
2. Use Salesforce Lightning Design System (SLDS): For consistent
UI design.
3. Lazy Loading: Load components or data only when necessary.
4. Security Practices: Use Salesforce Locker Service to prevent
vulnerabilities like cross-site scripting.
@wire(getMenuItems) menuItems;
handleMenuUpdate() {
// Perform some update action
refreshApex(this.menuItems); // Refresh the cached data
}
100. What are the different data binding types in LWC compared to
Aura?
In Aura, data binding is typically two-way, meaning changes in the data
model reflect in the UI and vice versa without extra code. In LWC, data
binding is one-way by default, making it more predictable and easier to
debug.
101. What are styling hooks in LWC, and why are they important?
Styling hooks allow developers to override the default styles of SLDS
components to match their branding. They are important for maintaining
brand consistency across custom components.
:host {
--slds-c-button-brand-color-background: #ff6600; /* Customize button
color */
}
102. What is the purpose of the XML configuration file in an LWC
bundle?
Answer: The XML configuration file in an LWC component bundle
defines the component's metadata, including where it can be used (e.g.,
in an app page, record page, or utility bar) and any design attributes
available for customization in the Lightning App Builder.
Code Snippet:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle
xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>53.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>
103. What does the <isExposed> tag in the XML configuration file
signify?
The <isExposed> tag indicates whether the LWC component is exposed to
the Lightning App Builder. If set to true, the component can be added to
Lightning pages, such as record pages, app pages, and home pages.
Code Snippet:
<isExposed>true</isExposed>
104. How do you specify where an LWC component can be used in the
XML configuration file?
The <targets> and <target> tags define where the component can be used
within Salesforce, such as on record pages, app pages, home pages, and
in utilities like the utility bar. The <targetConfigs> tag can further specify
details for each target, like which objects the component can be associated
with.
Code Snippet:
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
<target>lightning__UtilityBar</target>
</targets>
105. What is the <targetConfig> tag used for in the XML configuration
file?
The <targetConfig> tag specifies additional configuration details for each
target, such as limiting the component's usage to specific Salesforce
objects or setting design attributes that can be configured in the Lightning
App Builder.
Code Snippet:
<targetConfigs>
<targetConfig targets="lightning__RecordPage">
<objects>
<object>Account</object>
<object>Contact</object>
</objects>
</targetConfig>
</targetConfigs>
106. How can you control the visibility of an LWC component in the
Lightning App Builder?
Visibility can be controlled using the <isExposed> tag and through
<targetConfigs> by specifying criteria such as user profiles, permissions, or
specific conditions that must be met for the component to be displayed.
Code Snippet:
xml
<targetConfigs>
<targetConfig targets="lightning__RecordPage">
<objects>
<object>Account</object>
</objects>
<supportedFormFactors>
<supportedFormFactor type="Small" />
<supportedFormFactor type="Large" />
</supportedFormFactors>
</targetConfig>
</targetConfigs>
108. What are design attributes in LWC, and how are they configured
in the XML file?
Design attributes are customizable properties of an LWC component that
can be set in the Lightning App Builder. They allow users to configure
component behavior or appearance without changing the code, defined
under the <design> tag in the XML configuration file.
Code Snippet:
<design>
<attribute name="backgroundColor" label="Background Color"
type="String" />
<attribute name="title" label="Section Title" type="String" />
</design>
110. What are the key properties defined in the XML configuration file
of an LWC component?
• apiVersion: Specifies the Salesforce API version.
• isExposed: Determines if the component is available in the Lightning
App Builder.
• targets: Lists the areas in Salesforce where the component can be
used, such as record pages, app pages, or community pages.
• targetConfigs: Provides detailed settings for each target, including
object-specific configurations and design attributes.
111. How are SVG files used in LWC, and what is their significance in
the component bundle?
Answer: SVG files in LWC are used to define custom icons for the
component. These icons appear alongside the component’s name in the
App Builder or when the component is used in the UI. The SVG file
provides a scalable graphic that enhances the component’s visual identity.
112. What is Lightning Locker Service, and why is it important?
Lightning Locker Service is a security framework that isolates Lightning
components, ensuring that each component's data and DOM are protected
from others. It prevents common security vulnerabilities like cross-site
scripting (XSS) and ensures secure execution of JavaScript code.
Imagine a large, busy restaurant with several specialized sections: the
kitchen, the bar, and the front desk (for reservations and payments). Each
section needs to operate independently but also securely within the same
environment, ensuring that one section's actions or data do not adversely
affect another.
// Component B
<template>
<div class="component-b">Component B</div>
</template>
In this example, Component A and Component B cannot manipulate each
other's DOM elements directly due to Locker Service's isolation.
119. What are the key differences between using LMS and traditional
event handling in Salesforce?
Answer: LMS is designed for cross-component and cross-framework
communication, allowing LWCs, Aura components, and Visualforce pages
to communicate seamlessly. Traditional event handling, such as using
custom events, is typically limited to components within the same hierarchy
or framework.
121. What is Lightning Message Service (LMS) and how does it differ
from Pub/Sub?
Imagine a large restaurant chain that has multiple systems, like the kitchen
display, order-taking system, and delivery tracking. These systems are built
using different technologies. For example, the kitchen display might be a
traditional web application, the order-taking system might be an advanced
web component, and the delivery tracking might be on a Visualforce page.
LMS acts like a central dispatcher for messages. If an order status changes
(e.g., an order is ready for pickup), the LMS can notify all systems,
regardless of their technology. So, the kitchen can update the display, the
waitstaff can see the status change on their order-taking system, and the
delivery tracking system updates for the delivery staff.
Pub/Sub is great for simple, direct messaging where the sender and
receiver don't need to be tightly integrated. It's easier to implement for
basic needs, but lacks the cross-platform capabilities of LMS.