Concepts or coding lessons of Salesforce that you can implement easily

Showing posts with label LWC. Show all posts
Showing posts with label LWC. Show all posts

Lightning Web Component Interview Questions - Part 3

 Below are few questions which are asked me during my latest interviews : 

 22. I want to pass data from HTML file of Parent to Child in LWC?

Ans: WE can use slots to pass data from HTML file of Parent to Child.


23. What are the slots in LWC, explain with code ?

Ans: Slots allows component to interact, display and receive dynamic content from parent components.

Parent.html

<template>

  <c-child-slot>

    <p> i am unnamed slot</p>

    <p slot="first"> i am unnamed slot new !</p>

  </c-child-slot>

</template>


ChildSlot.html

<template>

  <slot></slot>

  <slot name="first" onslotchange={handlechange}></slot>

</template>


Child.js

import { LightningElement } from 'lwc';

export default class ChildSlot extends LightningElement {

  handlechange(){

    console.log('in handlechange');

  }

}

OUTPUT: 


24. What are the benefits slots in LWC?

Ans: 

  • Slots enable LWC components to interact dynamic content provided by Parent LWC. 
  • This helps in building of complex UI with multiple components.
  • Slots provides reusability, as its allows Child LWC to work with different Parent LWC.
  • Slots simplifying the overall application architecture.

25. What are the Promises in LWC?

Ans: In LWC, when we have to call methods Asynchronously, we can use Promises. Promises handles asynchronous operations and provide bettor error handling than events and callback.

Syntax: 

var objPromise = new Promise(Function(resolve, reject)){

    // your async code.

});

Promise takes one argument which is a callback function. Callback function have 2 parameters, resolve and reject. If everything works well then call resolve else reject.

Promises have 3 steps: Pending, Fulfilled, Rejected.


26. When to use @wire call?

Ans:

  • We can use wire when we have to cached the Result. 
  • @wire adaptor are great to read the apex data.
  • DML are not supported in @wire.

27. When to use Imperative call?

Ans:
  • When we have to do DML operations on database.
  • Data cannot be cached.

28. Why we set super() in LWC constructor?

Ans: Constructor must have super() as first statement. This establishes the correct prototype chain and value for "this" keyword.


29. What is the use of this keyword in LWC?

Ans:  this keyword is used to gain access of property or method of any LWC component. this referred to calling context of current piece of code.


30. Why we use @track decorator?

Ans:  @track decorator is use to make variable Private and track Private reactive properties in LWC.


31. Why we use @api decorator?

Ans:  @api decorator is use to make variable Public and track Public reactive properties in LWC.


Subscribe blog for More updates !!! 



Read More: Lightning Web Component Interview Questions - Part 1
                    


Latest Salesforce Interview Questions and Answers:

Get records from different Objects using Wire Method

How to use @Wire to get data for Batch of records ??

In LWC project, we usually have scenario where we have to retrieve different records from different object. For this we use Wire method but are you using 2 wire methods for this ?

Then you are doing multiple calls which decreases performance. 

LWC have 'getRecords' using this we can use wire adapter to get data for a batch of records at once.

As this process in Batch style, this reduces the number of network calls which indirectly increases LWC performance.

Syntax:

@wire(getRecords, { records: [ { recordIds: string[], fields: string[] } ] })


This will return 2 parameters
Results which is batch result
hasErrors which indicates if any result is failed.


Note : If you want to get data for a single record, use getRecord instead.


Here is the example you can use:

import { LightningElement, wire } from 'lwc';
import { getRecords } from 'lightning/uiRecordApi';
import CONTACT_EMAIL_FIELD from '@salesforce/schema/Contact.Email';
import USER_EMAIL_FIELD from '@salesforce/schema/User.Email';
import USER_NAME_FIELD from '@salesforce/schema/User.Name';

export default class RecordPickerDemo extends LightningElement {
    @wire(getRecords, { 
        records: [
            {
                recordIds : ['0050XXXXXX8QSMo'],
                fields: [USER_EMAIL_FIELD],
                optionalFields: [USER_NAME_FIELD],
            },
            {
                recordIds : ['0032XXXXXXnuFFf'],
                fields: [CONTACT_EMAIL_FIELD],
            },
        ],
    })
    wiredRecords;
}

Easily Iterate Map in Lightning Web Component

In LWC project, we usually stuck how to iterate Map in Lightning Web Component
Here is the example you can use to iterate Map.

1. Create Apex class StudentController.cls:

public class StudentController {
@AuraEnabled(cacheble=true)
public static Map<String, String> fetchStudentData(){
Map<String, String> mapStudentData = new Map<String, String>();
mapStudentData.put('Om','BCS');
mapStudentData.put('Sai','BTech');
mapStudentData.put('Ram','BE Computer Science');
mapStudentData.put('Radhe','BE Civil');
return mapStudentData;
}
}


2. Create LWC LWCStudentMap.html:

<template>
    <lightning-card icon-name="standard:account" variant="base" title="LWC Map Demo">
      <table class="slds-table slds-table_cell-buffer slds-table_bordered">
        <thead>
            <tr class="slds-line-height_reset">
                <th scope="col"> Name </th>
                <th scope="col"> Faculty </th>
            </tr>
        </thead>
        <tbody>
            <template for:each={mapStudentData} for:item="objMap">
                <tr class="slds-hint-parent" key={objMap.key}>
                    <th scope="col">
                        <div title={objMap.key}> {objMap.key} </div>
                    </th>
                    <th scope="col">
                        <div title={objMap.value}> {objMap.value} </div>
                    </th>
                </tr>
            </template>
        </tbody>
      </table>>
    </lightning-card>
</template>


3. Create LWC LWCStudentMap.js:

import { LightningElement, track, wire } from 'lwc';
import fetchStudentData from '@salesforce/apex/StudentController.fetchStudentData'

export default class LWCStudentMap extends LightningElement {
    @track mapStudentData = [];
    @track error;

    @wire(fetchStudentData)
    wiredData({ error, data }) {
      if (data) {
        console.log('Data', data);
        var consts = data;
        for(var key in consts)
            this.mapStudentData.push({value:consts[key], key:key});
      } else if (error) {
        console.error('Error:', error);
        this.error = error;
      }
    }
}


Output: 


Subscribe blog for More updates !!! 


Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 


Latest Salesforce Interview Questions and Answers:

Lightning Web Component Interview Questions - Part 2

 11. Can I use multiple decorators for one property?

Ans:No, we cant use multiple decorators for same property.

12. 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.

13. How to navigate user from LWC component to record detail page?

Ans: We can do it using NavigationMixin service.

14. 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’

15. When do we face error of “Cant assign to Read only property” in LWC?

Ans: This error generally occurs on update of public property @api decorator variable value. Ideally you should clone the value then make the changes to it.

16. How can you make a Lightning Web Component available for use in the Salesforce App Builder?

Ans: You need to define a custom component in the meta.xml file of your LWC and set the isExposed attribute to true.

17. How do you make an HTTP callout from a Lightning Web Component?

Ans: 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.

18. LWC has the @wire decorator to get the data from apex. But you are not getting the data from the server. What could be one of the reason?

Ans: First check whether you have used @AuraEnabled(cacheable=true) in the apex method.

19. How to get current record id in LWC

Ans: Use the 'lightning/pageReferenceUtils' module which provides utility functions to extract parameters, including the record ID, from the page URL.

        import { LightningElement } from ‘lwc’;

import { getRecordId } from ‘lightning/pageReferenceUtils’;

export default class MyComponent extends LightningElement {

recordId;

connectedCallback() {

this.recordId = getRecordId();

}

}

20. How to ensure that LWC respects FLS?

Ans: a. Check FLS in Apex :

Use the 'SECURITY_ENFORCED' annotation. The 'WITH SECURITY_ENFORCED' clause ensures that the query respects FLS, throwing an exception if the user lacks the necessary permissions.

public with sharing class AccountController {

@AuraEnabled(cacheable=true)

public static Contact getCon(Id conId) {

return [SELECT Id, Name FROM Contact WHERE Id = :conId WITH SECURITY_ENFORCED];

}

}

 b. Use Schema Methods in Apex

 c. Use Standard Components Where Possible: Use Lightning Data Service components


21. How do you use the Salesforce REST API in LWC ?

Ans: We can use the built-in fetch method to make API callout from LWC

import { LightningElement } from ‘lwc’;

export default class MyAPIComponent extends LightningElement {

connectedCallback() {

const endpoint = '/services/data/v53.0/query?q=SELECT+Name+FROM+Contact';

fetch(endpoint, {

method: 'GET',

headers: {

'Authorization': 'Bearer ' + authToken

}

})

.then(response => {

return response.json();

})

.then(data => {

console.log('Data '+data);

})

.catch(error => {

console.error('error '+error);

});

}


Subscribe blog for More updates !!! 



Read More: Lightning Web Component Interview Questions - Part 1
                    


Latest Salesforce Interview Questions and Answers:

Lightning Web Component Interview Questions - Part 1

1. We extends LightningElement in LWC, What is the reason?

Ans: LightningElement is custom wrapper on HTMLElement which actually contains all the lifecycle hooks methods like connectedCallback(), disconnectedCallback(), renderedCallBack(). We can use this methods in LWC

2. What is the Lifecycle in LWC?

Ans:

a. Parent Constructor is called

b. Public property are set on parent

c, Parent is inserted to DOM

d. Once parent is inserted to DOM, Connected callback is called on parent

e. From this connected callback as parent is already inserted, you can reference different DOM elements.

f. Parent is rendered

g. Once parent is rendered, Constructor is called on the child

h. Public property of child are set

i. Child is inserted to DOM

j. Once child is inserted to DOM, Connected callback is called on child

k. Child is rendered

l. Once child is rendered, child rendered callback is called

m. Once child rendered callback is called, then parents rendered callback is called.

3. Is @wire method called multiple times during lifecycle of component in LWC ?

Ans:Yes, @wire method called multiple times in LWC

4. If we parent component X and there are two component Y and Z as child components. How can we communicate between Y and Z ?

Ans: We should fire up event from child component Y to parent X then from parent X call attribute / function exposed (as @api) and pass data into Z component.

5. Can we do DML in method annotated with @AuraEnabled(cacheable= true)?

Ans: No, we cannot do DML inside any method annotated with cacheable = true , we will receive an error as DMLLimit Exception.

6. Can we call function annotated with @AuraEnabled(cacheable= true) imperatively ?

Ans: Yes

7. How to refresh cache when calling method imperatively?

Ans: We have to use getRecordNotifyChange(RecordIds) which refreshes the Lightning Data Service 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.

8. What happens when bubbles : false and composed : false (Default behavior)?

Ans:This is the default behavior, and bubbles and composed are not required to be defined explicitly.

When this is in effect, the event would not bubble up the DOM, as well as it would not cross shadow boundary.

We can listen these event only via defining the event handler to component that fires the event.

9. What happens when bubbles : true and composed : false ?

Ans:  In this behavior, the event bubbles up the DOM, but don’t cross the shadow boundary. In simple terms, It bubbles up inside the current template, in which event is fired, but it would not cross it’s boundary.

For example :- There are two component, where parent component contain child component. If event is fired inside child component, the event only bubbles up inside child component, and it would not cross it’s boundary, and parent component will not be able to listen this event.

10. What does composed : true does in an event ?

Ans: These types of events can bubble up inside DOM and also able to cross shadow boundary.

    For example :- There are two component, where parent component contain child component. If event is fired inside child component, the event bubbles up and it would cross it’s boundary, and parent component will be able to listen this event.


Subscribe blog for More updates !!! 



Latest Salesforce Interview Questions and Answers:

Salesforce Interview Questions - Part 7



More Salesforce Blogs:

Difference Between Indirect Lookup and External Lookup In Salesforce
What is the use of nextStartDate in Salesforce?
Check out Salesforce Daily Limit Only in 5 Simplest Steps
Learning Pagination In Salesforce Is Not Difficult At All ! You Just Need 3 Easy Steps
How To Learn Get Field Values From Visualforce Page To Apex Class Controller Without Losing Your Mind
Main Difference Between ISBLANK And ISNULL in Salesforce
How To Get Total Amount Of Records Processed In Batch Job In 10 Minutes And Still Look Your Best 
Export VisualForce Data into Excel Sheet in 3 Easiest Steps
7 Easy Steps to Generate Apex Class From WSDL In Salesforce
Simplest Way To Find Number of Days Between Two Dates in Salesforce
3 Easy Steps To Send Emails With Attachment From Your Apex Class In Salesforce
How Insert Comma In Formula Fields Can Help You Improve Your Productivity
Simple Guidance For You In Access Of Subquery Field Value Using Apex - Upwards Traversal.
Access Subquery Field Value Using Apex in 2 Easy Steps- Downwards Traversal


How Learning Enable Inline Editing In Visual Force Pages Could Save Your Money And Time

Easily Get Custom Labels in LWC

In this blog we are going to learn how we can access custom labels in LWC

To access custom label use below syntax:

import varName from '@salesforce/label/c.companyDiscount';

Create Custom Label :



customLabels.html

<template>
<div class="slds-m-around_small"> 
Company Discount is => {discountDetails}
</div>
</template>

customLabels.js

import { LightningElement, track } from 'lwc';

import companyDiscount from '@salesforce/label/c.companyDiscount';

export default class CustomLabels extends LightningElement {

    @track discountDetails = companyDiscount;

}

Output:




 

Subscribe blog for More updates !!! 



Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 


Latest Salesforce Interview Questions and Answers:

Easily Navigate from one LWC to another LWC

 Here we are going to see Navigate from one LWC to another LWC.

To Navigate from one LWC to another LWC, we need to add LWC component into AURA component. and in Aura component we have to implements "lightning:isUrlAddressable".

In this example, i have create 2 LWC components (sourceLWC, targetLWC) and 1 AURA component - NavigateAuraToLWC.

1. sourceCmp.html

<template>
    <lightning-card icon-name="custom:custom35" variant="Narrow" title="Source LWC">
      <div class="slds-var-p-horizontal_small">
        <lightning-button
          variant="brand"
          label="Navigate"
          onclick={handleClick}
        ></lightning-button>
      </div>
    </lightning-card>
</template>

sourceCmp.js

import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';

export default class SourceCmp extends NavigationMixin(LightningElement) {
    handleClick(){
        let pageRef = {
            type : "standard__component",
            attributes: {
             componentName: "c__NavigateAuraToLWC"// namespace + __ + aura component
            },
            state:{
                c__codeName: 'Status'
            }
        };

        this[NavigationMixin.Navigate](pageRef);
    }
}

sourceCmp.js-meta.xml

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

2. NavigateAuraToLWC.cmp

<aura:component implements="flexipage:availableForAllPageTypes,
        lightning:isUrlAddressable" access="global">

    <aura:attribute type="String" name="codeName"/>

    <aura:handler name="init" value="{!this}" action="{!c.init}"/>
    {!v.codeName}

    <div class="slds-card">
        <c:targetCmp codeName="{!v.codeName}"/>
    </div>
</aura:component>  

NavigateAuraToLWCController.js

({
    init : function(component, event, helper) {        
        alert('in init');
        // myPageReference give "pageRef" varible created in sourceCode.js LWC
        var myPageReference = component.get("v.pageReference");
        // Access state parameter
        var propertyValue = myPageReference.state.c__codeName;
        alert('propertyValue=> '+propertyValue);
        component.set('v.codeName', propertyValue);
    }
})


3. targetCmp.html

<template>
    <lightning-card icon-name="custom:custom12"
        variant="Narrow" title="Target LWC">
      <div class="slds-var-p-around_large">
       <h1>I am in LWC target component : {codeName}</h1>
      </div>
    </lightning-card>
</template>


targetCmp.js

import { LightningElement, api } from 'lwc';

export default class TargetCmp extends LightningElement {
    @api codeName;
}


targetCmp.js-meta.xml

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

Output: 

After adding sourceCmp component into home page, 


Once Click on Navigate button, it shows below :


Subscribe blog for More updates !!! 


Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 


Latest Salesforce Interview Questions and Answers: