About Me

My photo
PLANO, Texas, United States

Wednesday, September 23, 2020

Call Apex Imperatively

This article explains about detail information about imperatively Apex call. To get more high-level details about how apex can be called from LWC, please, check my previous article.

  • Call Apex imperatively when you need to control the invocation of read operations, and when you modify records. 

  • You can call both cacheable and non-cacheable Apex methods imperatively. To refresh the cache for a cacheable method, call the method again.

  • The imported function returns a promise.

Before going to deep drive in the imperative way of apex in LWC, you should know about Promise.

Promise

Imagine that you’re a top singer, and fans ask day and night for your upcoming single.

To get some relief, you promise to send it to them when it’s published. You give your fans a list. They can fill in their email addresses so that when the song becomes available, all subscribed parties instantly receive it. And even if something goes very wrong, say, a fire in the studio, so that you can’t publish the song, they will still be notified.

Everyone is happy: you because the people don’t crowd you anymore, and fans, because they won’t miss the single.

This is a real-life analogy for things we often have in programming:

  1. A “producing code” that does something and takes time. For instance, some code that loads the data over a network. That’s a “singer”.

  2. A “consuming code” that wants the result of the “producing code” once it’s ready. Many functions may need that result. These are the “fans”.

  3. A promise is a special JavaScript object that links the “producing code” and the “consuming code” together. In terms of our analogy: this is the “subscription list”. The “producing code” takes whatever time it needs to produce the promised result, and the “promise” makes that result available to all of the subscribed code when it’s ready.

The properties state and result of the Promise object are internal. We can’t directly access them. We can use the methods .then/.catch/.finally for that.

Consumes: then,catch,finally

A Promise object serves as a link between the executor (the “producing code” or “singer”) and the consuming functions (the “fans”), which will receive the result or error. Consuming functions can be registered (subscribed) using methods .then, .catch and .finally.


promise.then(

  function(result) { /* handle a successful result */ },

  function(error) { /* handle an error */ }

);

// .catch(f) is the same as promise.then(null, f)

promise.catch(alert);

With similar way, you can call apex method from LWC. javascript. Pls check below example:


Create Apex Class-

public with sharing class GetAccountData {

   @AuraEnabled(cacheable=true)

   public static List<Account> getAccountList(){

       return [Select Id,

                      Name,

                      Type,

                      Rating,

                      Phone from Account];

      

   }

  

}


Create Blog_ImperativeApex.htm-

<template>

   <lightning-card title="Apex Imperative Method Example">

       <div class="slds-m-around_medium">

           <p class="slds-m-bottom_small">

               <lightning-button label="Load Accounts" onclick={handleLoad}></lightning-button>

           </p>

           <template if:true={accounts}>

               <template for:each={accounts} for:item="account">

                   <p key={account.Id}>{account.Name}</p>

               </template>

           </template>

           <template if:true={error}>

              {error}

           </template>

       </div>

   </lightning-card>

</template>

Create Blog_ImperativeApex.js

import { LightningElement, wire,track  } from 'lwc';

import getAccountList from '@salesforce/apex/GetAccountData.getAccountList';

export default class ImperativEx extends LightningElement {

   @track accounts;

   @track error;

   handleLoad() {

       console.log('This is start of the method');

       getAccountList()

           .then(result => {

               this.accounts = result;

               console.log('This i result'+result);

           })

           .catch(error => {

               this.error = error;

               console.log('This i error'+error);

           });

   }

}


Deploy the LWC to salesforce org and add to the lighting page



Common Errors

Issue- When we deploy LWC to salesforce org, the 1st time you might not be able to see the data.
Solution- you can clear the cache and refresh the browser.
Warning- Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig' to remove this warning.ts(1219)
Solution- You need to add a jsconfig.json file within your LWC file. You might see this file in your project but you need to copay paste in LWC component file.

1 comment:

  1. Very nice explanation using real world example. Thanks for sharing your knowledge.

    ReplyDelete