Imperative apex call

Imperative apex call:-

            If  an  apex class is  not annotated  with cacheable = true  the only option to call it in LWC  is imperative apex call. since  cacheable methods can't perform DML operations.

When  dml is needed the only way to call such method in lwc is Imperative apex approach.

This method will return the Promise. Hence we need to handle the Success and Failure response using then and error function respectively. 

While making imperative call to server  the response is served directly in the object and you don't need property.data.

Can perform DML too.

Can work with objects not supported by User Interface API(Task,Event).


     Syntax :-   

                        javascriptFunctionName(){
                         import apexMethodName (parameter)
                                     .then( result=> {                                  // whatever results(records) we get 
                                        // do process here                                  from apex method in apex class 
                                          })                                                             stored in the result
                                        .catch ( error => {
                                              this //error handler 
                                            })
                                       }
                                 }
    Ex:-

imperativeLwc .html:-

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

imperativeLwc.js:-

import { LightningElement, wire,track } from 'lwc';
import getAccountList from '@salesforce/apex/GetAccountData.getAccountList';
export default class ImperativeLwc  extends LightningElement {
    @track accounts;
    @track error;
    handleLoad() {
        getAccountList()
            .then(result => {
                this.accounts = result;
            })
            .catch(error => {
                this.error = error;
            });
    }
}

Comments

Popular posts from this blog

Security model

EVENTS IN Lightning Web Components

Lightning web Components.