How to call the apex method and retrieve list of records using (Imperatively and Wire Service) in LWC – Lightning Web Component | How to Invoke apex method imperatively and “@wire” method and fetch list of records uses of “@salesforce/apex/” library in Lightning Web Component (LWC) Salesforce

4,842 views

Hey guys, today in this post we are going to learn about How to Call the Apex Method and retrieve list of records using (Imperatively and Wire Service) in LWC – Lightning Web Component.

Call Apex Methods Imperatively →

To control when the method invocation occurs (for example, in response to clicking a button), call the method imperatively. When you call a method imperatively, you receive only a single response. Compare this behavior with @wire, which delegates control to the framework and results in a stream of values being provisioned.

In the following scenarios, you must call an Apex method imperatively as opposed to using @wire.

  • To call a method that isn’t annotated with cacheable=true, which includes any method that inserts, updates, or deletes data.
  • To control when the invocation occurs.
  • To work with objects that aren’t supported by User Interface API, like Task and Event.
  • To call a method from an ES6 module that doesn’t extend LightningElement

If an Apex method is marked with @AuraEnabled(cacheable=true), a client-side Lightning Data Service cache is checked before issuing the network call to invoke the Apex method on the server. To know more about Imperatively service, Click Here →

Wire Apex Methods in LWC →

Lightning web components use a reactive wire service. Use @wire in a component’s JavaScript class to specify an Apex method. You can @wire a property or a function to receive the data. To operate on the returned data, @wire a function.

To use @wire to call an Apex method, annotate the Apex method with @AuraEnabled(cacheable=true). A client-side Lightning Data Service cache is checked before issuing the network call to invoke the Apex method on the server. To refresh stale data, call refreshApex(), because Lightning Data Service doesn’t manage data provisioned by Apex. To know more details about Wire Apex Methods, Click Here →

 

Files we used to Imperatively and Wire Service in Lightning Component →

lwcImperativeWire.html LWC HTML File Template HTML file to fetch the records uses of Imperatively and Wire service in (LWC)
lwcImperativeWire.js LWC JavaScript File In the javascript file we import the @salesforce/apex/ library in Salesforce LWC
lwcImperativeWire.css Style CSS It is used to fixed the alignment of the data table as padding and border in lwc component.
lwcImperativeWire.js-meta.xml XML Meta File It is used to where this lightning web component file you want to display as lightning__AppPage, lightning__RecordPage, lightning__HomePage.
lwcImperativeWireApp.app Lightning Application It is used to call the component to preview on browser.

 

 

Final Output →

imperatively and wire service in lwc -- w3web.net

 
 

You can download file directly from github by Click Here.

 
✪ The Big Announcement: -
As per student's demands, I re-opened my eBook of "Salesforce Tutorial" Limited-time huge discount offer Absolutely 50% Off.
I am thinking to give you discount offer occasion of Gandhi Jayanti for a powerful "Salesforce admin course" where you can Understand from Basic Concepts to advanced label in Salesforce.
👉 So Don't MISS it... (Access Right Now)
👉 Get Huge Discount Offer 50%: - Get eBook
 

 
 

Other related post that would you like to learn in Salesforce

  • Find the below steps ▾

 

Create Lightning Web Component HTML →

Step 1:- Create Lightning Web Component : lwcImperativeWire.html

SFDX:Lightning Web Component >> New >> lwcImperativeWire.html

lwcImperativeWire.html [Lightning Web Component HTML]

  1.    <template>
  2. <div class="slds slds-p-around_large">    
  3. <!--Start Imperative method-->
  4.  <div style="text-align:center;"><lightning-button variant="brand" label="Get Account" onclick={accountsAction}></lightning-button></div>
  5. <br/>
  6.  
  7. <lightning-card icon-name="standard:account" title="Using Imperative method to retrieve Account records">
  8.  
  9. <table class="tblColPad" border="1" cellpadding="5" cellspacing="5" style="border-collapse:collapse;"> 
  10.  
  11.     <thead>
  12.         <tr>
  13.             <th>Name</th>
  14.             <th>Phone</th>
  15.             <th>Industry</th>
  16.             <th>Type</th> 
  17.         </tr>
  18.     </thead>
  19.     <tbody>  
  20. <template for:each={accList} for:item="accItem">
  21. <tr key={accItem.Id}>
  22.     <td>{accItem.Name}</td>
  23.     <td>{accItem.Phone}</td>
  24.     <td>{accItem.Industry}</td>
  25.     <td>{accItem.Type}</td>   
  26. </tr>
  27.  
  28. </template>
  29. </tbody>
  30. <tfoot>
  31.     <tr>
  32.         <td colspan="4"><a href="https://www.w3web.net/tutorial/salesforce-lwc/" target="_blank" rel="noopener noreferrer">[To get more examples of lwc..]</a></td>
  33.     </tr>
  34. </tfoot>
  35. </table>
  36. </lightning-card>
  37.  
  38.  
  39. <!--Close Imperative method-->
  40. <br/><br/>
  41.  
  42.  
  43. <!--Start @wire decorator-->
  44.  
  45. <lightning-card icon-name="standard:lead" title="Using @wire decorator  to retrieve Lead records">
  46.  
  47. <table class="tblColPad" border="1" cellpadding="5" cellspacing="5" style="border-collapse:collapse;">    
  48. <thead>   
  49.  <tr>
  50.     <th>Name</th>
  51.     <th>Title</th>
  52.     <th>Phone</th>
  53.     <th>Email</th>
  54. </tr>
  55. </thead>
  56.  
  57. <tbody>
  58. <template for:each={leadList} for:item="leadItem">    
  59.     <tr key={leadItem.Id}>
  60.         <td>{leadItem.Name}</td>
  61.         <td>{leadItem.Title}</td>
  62.         <td>{leadItem.Phone}</td>
  63.         <td>{leadItem.Email}</td>
  64.     </tr>        
  65. </template>
  66. </tbody>
  67. <tfoot>
  68.     <tr>
  69.         <td colspan="4"><a href="https://www.w3web.net/tutorial/salesforce-lwc/" target="_blank" rel="noopener noreferrer">[To get more examples of lwc..]</a></td>
  70.     </tr>
  71. </tfoot>
  72. </table>
  73.  
  74. </lightning-card>
  75.  
  76. <!--Close @wire decorator-->
  77.  
  78.  
  79. <!--Start RelatedTopics Section-->
  80. <div style="border:1px #ddd solid; padding:10px; background:#eee; margin:40px 0;">
  81.  
  82.     <p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/05/thumbsUpLike.png" width="25" height="25" style="vertical-align:top; margin-right:10px;"/><strong data-aura-rendered-by="437:0"><span style="font-size:16px; font-style:italic; display:inline-block; margin-right:5px;">Don't forget to check out:-</span><a href="https://www.w3web.net/" target="_blank" rel="noopener noreferrer" style="text-decoration:none;" data-aura-rendered-by="440:0">An easy way to learn step-by-step online free Salesforce tutorial, To know more Click  <span style="color:#ff8000; font-size:18px;" data-aura-rendered-by="442:0">Here..</span></a></strong></p>
  83.  
  84.             <br/><br/>
  85.         <p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/07/tickMarkIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;"/><strong data-aura-rendered-by="437:0"><span style="font-size:17px; font-style:italic; display:inline-block; margin-right:5px; color:rgb(255 128 0);">You May Also Like →</span> </strong></p>
  86.             <div style="display:block; overflow:hidden;"> 
  87.                 <div style="width: 50%; float:left; display:inline-block">
  88.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  89.                         <li><a href="https://www.w3web.net/lwc-get-set-lightning-checkbox-value/" target="_blank" rel="noopener noreferrer">How to get selected checkbox value in lwc</a></li>
  90.                         <li><a href="https://www.w3web.net/display-account-related-contacts-in-lwc/" target="_blank" rel="noopener noreferrer">how to display account related contacts based on AccountId in lwc</a></li>
  91.                         <li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to create lightning datatable row actions in lwc</a></li>
  92.                         <li><a href="https://www.w3web.net/if-and-else-condition-in-lwc/" target="_blank" rel="noopener noreferrer">how to use if and else condition in lwc</a></li>
  93.                         <li><a href="https://www.w3web.net/get-selected-radio-button-value-and-checked-default-in-lwc/" target="_blank" rel="noopener noreferrer">how to display selected radio button value in lwc</a></li>
  94.                     </ul>
  95.             </div>
  96.  
  97.             <div style="width: 50%; float:left; display:inline-block">
  98.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  99.                         <li><a href="https://www.w3web.net/display-account-related-contacts-lwc/" target="_blank" rel="noopener noreferrer">display account related contacts based on account name in lwc</a></li>
  100.                         <li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to insert a record of account Using apex class in LWC</a></li>
  101.                         <li><a href="https://www.w3web.net/fetch-picklist-values-dynamic-in-lwc/" target="_blank" rel="noopener noreferrer">how to get picklist values dynamically in lwc</a></li>
  102.                         <li><a href="https://www.w3web.net/edit-save-and-remove-rows-dynamically-in-lightning-component/" target="_blank" rel="noopener noreferrer">how to edit/save row dynamically in lightning component</a></li>
  103.                         <li><a href="https://www.w3web.net/update-parent-object-from-child/" target="_blank" rel="noopener noreferrer">update parent field from child using apex trigger</a></li>
  104.                     </ul>
  105.                 </div>
  106.                <div style="clear:both;"></div> 
  107.                <br/>
  108.                 <div class="youtubeIcon">
  109.                     <a href="https://www.youtube.com/channel/UCW62gTen2zniILj9xE6LmOg" target="_blank" rel="noopener noreferrer"><img src="https://www.w3web.net/wp-content/uploads/2021/11/youtubeIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;"/> <strong>TechW3web:-</strong> To know more, Use this <span style="color: #ff8000; font-weight: bold;">Link</span> </a>
  110.                 </div>
  111.     </div> 
  112. </div>
  113.  
  114.   <!--End RelatedTopics Section-->
  115. </div>
  116. </template>

 

Create Lightning Web Component JavaScript →

Step 2:- Create Lightning Web Component : lwcImperativeWire.js

SFDX:Lightning Web Component >> New >> lwcImperativeWire.js

lwcImperativeWire.js [LWC JavaScript File]

  1.    import { LightningElement,track,wire,api } from 'lwc';
  2. import getLeadList from '@salesforce/apex/lwcImperativeWireCtrl.getLeadList';
  3. import getAccountList from '    lwcImperativeWireCtrl.getAccountList';
  4.  
  5. export default class LwcImperativeWire extends LightningElement {    
  6.  
  7.     // Using imperative call to server 
  8.     @track accList ;
  9.     accountsAction(){
  10.         getAccountList().then(result => {
  11.             console.log('result#'+result);
  12.             this.accList = result;
  13.  
  14.         })
  15.         .catch(error => {
  16.             console.log('error#'+error);
  17.  
  18.         })
  19.     }
  20.  
  21.  
  22.    // Using @wire decorator call to server   
  23.  @track leadList ;
  24.    @wire (getLeadList)
  25.     contactList({error,data}){
  26.         if(error){
  27.             console.log('error is#'+error);
  28.         }
  29.         else if(data){
  30.             console.log('lead data#'+data);
  31.             this.leadList = data;
  32.         }
  33.  
  34.     }
  35.  
  36.  
  37. }

 

Create Lightning Web Component Meta XML →

Step 3:- Create Lightning Web Component : lwcImperativeWire.js-meta.xml

SFDX:Lightning Web Component >> New >> lwcImperativeWire.js-meta.xml

lwcImperativeWire.js-meta.xml [LWC Meta Data XML]

  1.    <?xml version="1.0" encoding="UTF-8"?>
  2. <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
  3.     <apiVersion>45.0</apiVersion>
  4.     <isExposed>true</isExposed>
  5.     <targets> 
  6.         <target>lightning__AppPage</target>
  7.         <target>lightning__RecordPage</target>
  8.         <target>lightning__HomePage</target>
  9.     </targets>
  10. </LightningComponentBundle>

 

Style CSS →

Step 4:- Create Style CSS : lwcImperativeWire.css

SFDX:Lightning Web Component >> New >> lwcImperativeWire.css

lwcImperativeWire.css [Style CSS]

  1.    table.tblColPad th{background:#ddd;}
  2. table.tblColPad th, table.tblColPad td {padding:5px !important;}

 

Create Apex Class Controller →

Step 5:- Create Apex Controller : lwcImperativeWireCtrl.cls

SFDX:Create Apex Class >> New >> lwcImperativeWireCtrl.cls

lwcImperativeWireCtrl.cls [Apex Class]

  1.    public WITH sharing class lwcImperativeWireCtrl {
  2.  
  3.       // USING Imperative method CALL TO server 
  4.       @AuraEnabled
  5.       public static List<Account> getAccountList(){
  6.           List<Account> accList = [SELECT Id, Name, Phone, Industry, TYPE FROM Account LIMIT 10];
  7.           RETURN accList;
  8.       }
  9.  
  10.  
  11.    // USING @wire decorator CALL TO server 
  12.     @AuraEnabled(cacheable=TRUE)
  13.     public static List<Lead> getLeadList(){
  14.         List<Lead> leadList = [SELECT Id, Name, Title, Phone, Email FROM Lead LIMIT 10];
  15.         RETURN leadList;
  16.     }
  17.  
  18.  
  19. }

 

Create Lightning Application →

Step 6:- Create Lightning Application : lwcImperativeWireApp.app

From Developer Console >> File >> New >> Lightning Application

lwcImperativeWireApp.app [Component Application File]

  1.    <aura:application extends="force:slds">
  2.   <c:lwcImperativeWire/>
  3. </aura:application>

 
imperatively and wire service in lwc -- w3web.net

 

Further post that would you like to learn in Salesforce

 

 

FAQ (Frequently Asked Questions)

How do you call Apex class imperatively in LWC?

To call the apex method imperatively, we need to import the method from @salesforce/apex/ module in variable accounts. Then we can use this variable to call the method and pass the parameters if required. This method will return the Promise.

How do I call LWC from Apex?

To call it from Wire Service, the method should be cacheable. Hence, add cacheable=true in @AuraEnabled. And in the LWC js controller, we need to write the import method using the @salesforce/apex/className.

How do you call an Apex class from a custom button in Salesforce?

To call an Apex class from custom button or link on the object detail page, create a VisualForce page and call the Apex class method via the action attribute to make it work. Following is some sample code showing how to do that. The action method invoked when this page is requested by the server.

Related Topics | You May Also Like

 
   
 
 

Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Leave a Comment