Lwc -> Apex : Salesforce
Tags: salesforce, apex, javascript, beginners
Published: 2021-10-24 12:48:37


### # Call Apex Methods Imperatively
Call Apex Methods Imperatively is very simple :

**1.** Import Apex Method in js file like below format :
```javascript
import apexMethodName from  '@salesforce/apex/Namespace.ApexClassName.MethodName';
```
**example** :
```javascript
import getAccountList from  '@salesforce/apex/AccountHelperClass.getAccountList';
```
**2.** **Call Apex Method as per your choice like below:**
*Here we are not passing any param to apex:*
```javascript
import { LightningElement, track } from  'lwc';
import getAccountList from  '@salesforce/apex/AccountHelperClass.getAccountList';
export  default  class  IterationComp  extends  LightningElement {
@track accountList = [];
@track error;
 loadAccountListData() {
 // here we are not sending any params to apex.
 // but if apex method requires params then,
 // we can pass like getAccountList({paramName : valueToPass})
 // instead of  getAccountList()
        getAccountList() 
            .then(result => {
                this.accountList= result;
            })
            .catch(error => {
                this.error = error;
            });
    }
}
```

> In above js code we have made a function `loadAccountListData()` inside this we are calling our apex method `getAccountList ` from our Apex class `AccountHelperClass` and storing result in our `accountList` variable.
 
> Imperative way basically uses promise to return the data and if any error occurs, it will be catch by our `catch` block.

> We are calling our apex method in js function, so that we can reuse it by calling the `this.loadAccountListData()` function in any other js function. so we need to just call `this.loadAccountListData` to call the apex if we want to, or you can simple use `getAccountList()` function in other function.

 - **Apex Class :**
In Imperative way, the `cacheable=true` is not required and thus it gives the ability to mutate the data inside apex method. But we can use it.
```java
public class AccountHelperClass {
    @AuraEnabled
    public static List<Account> getAccountList() {
        return [SELECT Id, Name FROM Account ];
    }
}
```

3. **Passing params to apex :**
Suppose if apex require params to be passed like below apex method:
```java
public class AccountHelperClass {
    @AuraEnabled
	public static List<Account> getAccountList(String searchKey) {
        String key = '%' + searchKey + '%';
        return [
            SELECT Id, Name FROM Account WHERE Name LIKE :key WITH LIMIT 10
        ];
    }
}
```
So our js code would become like below :
```javascript
import { LightningElement, track } from  'lwc';
import getAccountList from  '@salesforce/apex/AccountHelperClass.getAccountList';
export  default  class  IterationComp  extends  LightningElement {
@track accountList = [];
@track error;
 loadAccountListData() {
 let key = 'shivam';
        getAccountList({searchKey : key}) 
            .then(result => {
                this.accountList= result;
            })
            .catch(error => {
                this.error = error;
            });
    }
}
```

> we can call `loadAccountListData()` function on `onclick()`in html or if you want to call apex when the components load you can simply call in `connectedCallBack()` function.
### Calling Apex on Loading of Component :
To get data from apex whenever components load we can simply use `connectedCallback()` like below :
```javascript
import { LightningElement, track } from  'lwc';
import getAccountList from  '@salesforce/apex/AccountHelperClass.getAccountList';
export  default  class  IterationComp  extends  LightningElement {
@track accountList = [];
@track error;

// it runs whenever components loaded into DOM
connectedCallback() { 
	this.loadAccountListData();
}

 loadAccountListData() {
 let key = 'shivam';
        getAccountList({searchKey : key}) 
            .then(result => {
                this.accountList= result;
            })
            .catch(error => {
                this.error = error;
            });
    }
}
```
[Keep following lwc series for upcoming blogs on lwc components,](https://dev.to/shivamkapasia0/series/15139)