Lightning Web Component Interview Questions
Lightning Web Component Interview Questions
1. Can we call the @AuraEnabled function in the apex class using wire ?
Ans: Function also needs to have cacheable = true annotation ie should be like
@AuraEnabled(cacheable = true)
2. What do you mean by cacheable = true annotations ?
Ans: First of all when you mark function as cacheable = true it can only retrieve
data i.e. it cant have any DML.
It is used to improve component performance by quickly showing cached data
from client side storage without waiting for server trip.
Remember to refresh the stale data provisioned by Apex we have to use
refreshApex as LDS doesn’t manage data coming from Apex ( In case of wired
service)
3. @wire(getBoats,{boatTypeId : this.boatTypeId})
getBoats(error,data){}
Will the above code deploy? (Assuming all variables and apex class function
exists).
Ans: No it wont when passing a variable in wire you should always use $ along
with variable, it should be written like
@wire(getBoats,{boatTypeId : ‘$boatTypeId})
4. Why do we use $ when passing property in wire function, what does it
mean? [Latest Salesforce lightning interview questions and answeres]
Ans: $ prefix tells the wire service to treat values passed as a property of the
class and evaluate it as this.propertyName and the property is reactive. If the
property’s value changes, new data is provisioned and the component renders.
5. See the below code and answer the following question: [Scenario based
Salesforce Lightning Interview question with relevant answer]
If I want to refresh the wired data in the above function, can I call
refreshApex(this.someVar) ?
@wire(getBoats,{boatTypeId : ‘$boatTypeId’})
getBoats({error,data}){
if(data){
this.someVar = data;
this.error = undefined;
}
else if(error){
this.error = error;
this.someVar = undefined ;
}
}
Ans:
No we cant call refreshApex(this.someVar) rather refreshApex is called on whole
result provisioned from the wire service not just the data part, we will have to
rewrite it as below :
@wire(getBoats,{boatTypeId : ‘$boatTypeId’})
getBoats(result){
this.mainResult = result;
if(result.data){
this.someVar = result.data;
this.error = undefined;
}
else if(result.error){
this.error = result.error;
this.someVar = undefined ;
}
}
Now we can refresh data as refreshApex(this.mainResult)
6. Can we call a wire function inside a javascript function like below :
searchBoats(event){
@wire(getBoats,{boatTypeId: ‘$boatTypeId’}
getBoats(data,error){
}
}
Assume searchBoats is being called on click of button? Will I be able to deploy the
code ?
Ans: No you cant call it like this , code will not deploy. You will receive error as
leading decorators must be attached to class which means decorators like wire
can be directly under class only not inside any other function.
Similarly if you try to define variable with @track or api decorator inside a
function it will fail.
7. When is the wire method/property called in the lifecycle of a
component ?
Ans: Wired service is called right after component is created ie after constructor
and is again called when parameter that you are passing is made available.
8. What are lifecycle hooks in LWC ?
Ans: A lifecycle hook is a callback method triggered at a specific phase of a
component instance’s lifecycle.
There are following hooks supported in LWC :
Constructor : Called when the component is created.
Connectedcallback : Called when the element is inserted into a document. This
hook flows from parent to child.
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.
Disconnectedcallback : Called when the element is removed from a document.
This hook flows from parent to child.
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
9. Is wire method called multiple times during lifecycle of component ? (True /
False)
Ans: True
10.What is the difference in below two codes , will they both compile ? Give
same results ?
11.[tricky Salesforce Lightning Interview question with relevant answer]
Code 1 :
@wire(getBoats)
getBoats({data,error}){
if(data)
console.log(‘print here’);
Else if(error)
console.log(‘print in else’);
}
@wire(getBoats,{})
getBoats({error,data}){
if(data)
console.log(‘print here’);
Else if(error)
console.log(‘print in else’);
}
Ans: Both will compile they are same.
Is it mandatory to use data,error only in wired method, can I use some other
variable like below : Scenario based interview question with answers
@wire(getBoats)
getBoats({myData,myError}){
if(mydata)
console.log(‘i am in data’);
else if(myError)
console.log(‘I am in error’);
}
Will the code deploy successfully or I will receive an error ?
Salesforce Lightning LWC interview questions and answers
Ans: We cant use any other variable name other than data, error they are
hardcoded in wire service. Code will successfully deploy but wire service wont be
able to fetch any data.
10.What is the difference between event.StopPropogation() and
Event.preventDefault()?
Ans: stopPropagation prevents further propagation of the current event in the
capturing and bubbling phases. preventDefault prevents the default action the
browser makes on that event.
10.If we add required attribute in lightning-input , will I get an error on leaving
the field empty ?
Ans: No unless you also add logic in backend javascript file to actually throw an
error using checkValidity and reportValidity.
11.Are quick actions supported for LWC components ?
Ans: Quick actions are supported by LWC in Summer 21 or later orgs. LWC
quick actions are only supported on record pages.
12.How can i reference record ID of page in my component which is fired from
quick action.
Ans: 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
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.
10.What is a promise in async transactions? What are it different stages. [Latest
Salesforce lightning interview questions and answers]
Ans:
Promise is object returned in async transaction which notifies you about
completion or failure of transaction.
For example when you call apex imperatively it returns you a promise object
on the basis of object returned execution either goes into (then) ie transaction
was successful or (catch) which means transaction failed.
getData(function(x)
{
getMoreData(x, function(y)
{
getMoreData(y, function(z)
{ ... }
);
});
});
10.What are decorators in LWC (Lightning web components) in Salesforce?
Latest interview question.
Ans: The Lightning Web Components programming model has three
decorators that add functionality to a property or function. There are 3
decorators for LWC
@track , @wire, @api
10.When do I use @track on a property ? Do I still need it considering all
properties are by default reactive now?
Ans: After Spring 20 all the properties are made by default reactive ie we dont
need @track for primitive properties. We still need it for array or object type
properties
11.Can I use multiple decorators on one property ?
Ans: No we cant use multiple decorators on same property.
12.Can I deploy component with empty css file ?
Ans: No we cant do that
13.What is difference between var and let in JS ?
Ans: In simple words difference is var is function scoped while let is block
scoped
Var allows you to redeclare same variable while let will throw an error
Var variables are hoisted that is you can access them even before they are
declared in code its just they will return undefined value while with let it will
throw an error.
14.Is there any difference in how we add LWC component inside another LWC
component and inside AURA component ?
Ans: Difference is how they are added in the component.
LWC follows kebab case ie if you are adding any LWC component inside
another component you will have to add in kebab case form while in AURA it
will be added without kebab case for example :
We have component with name “childLWCComponent”
In LWC it will be added as <c-child-l-w-c-component/>
In Aura it will be added as <c:childLWCComponent/>
15.What is LMS ?
Ans: 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.
16.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
17.How can we navigate user from LWC component to record detail page?
Ans: Can be done using NavigationMixin service
18.Do we have force:createRecord equivalent in LWC?
Ans: Using navigation mixin only you can also create new record where you
define object , action as new and pass any default values you want to set.
19.What is render() , is it part of lifecycle hook? Why do we use it ?
Ans: Render is not part of lifecycle hook its a protected function, we only use it
if we have imported multiple templates in our component and we want to
render particular template on meeting certain criteria.
20.Can I get current user ID in LWC without apex?
Ans: Yes we can get current user ID without apex by simply importing
import Id from ‘@salesforce/user/Id’
21.What is difference between ‘==’ and ‘===’ ?
Ans: Both are used to compare two variables but == doesnt take data type into
consideration and does type coercion ie interpreter tries to automatically
convert data types to match the values while in === case if data type is not
same it will always return false.
For example :
2==”2” will return True (Type coercion happens)
2===”2” will return False ( No Type coercion)
22.What is String interpolation ? [important interview questions and Salesforce
Lightning]
Ans: It means simply when string literal is evaluated all the placeholders added
into it are calculated at run time and replaced in string with values. Place
holder can be anything a variable , expression even a function call. In javascript
its performed using (backtick).
For example:
const greeting = 'Hello';
const who = 'World';
<force:recordData aura:id=”recordEditor”
fields=”Name,BillingCity,BillingState”
recordId=”{!v.recordId}”
targetError=”{!v.recordError}”
targetRecord=”{!v.record}”
targetFields =”{!v.simpleRecord}”
mode=”EDIT” />
<h2>{!v.sObjectInfo.Label}</h2>
<div>{!v.body}</div>
</aura:component>
<div>
<a onclick=”{!c.deleteRecord}”>Del</a> |
<a onclick=”{!c.navigateToRecord}”><ui:outputText
value=”{!rec.Name}”/></a>
</aura:renderIf>
</div>
</aura:iteration>
</aura:component>