While creating the LWC component whenever you want to call an apex function you use the @wire function in it and pass parameter in it which has @track or @api decorator attached with it like @track id; or @api id; and whenever there is any change in the parameter the wire function gets fired but there may be a requirement in which you may need to call the apex function inside an LWC function. So for that, you can directly use the function name inside the LWC function.
Here is an example of the same. Supposedly there is a functionality in which you can apply a rule to multiple accounts and when you create the rule from a particular account you want to fetch the name and address from apex using id so you can prepopulate in the create a new form. For that, you can call the apex function directly inside the connectedCallBack. Here is a code for how this can be done.
- Create an apex function with code related to your requirement.
@AuraEnabled(cacheable = true)
public static Account getAccountDetails(String accountId){
Account eachAccount = new Account();
if (Account.sObjectType.getDescribe().isAccessible() && Schema.sObjectType.Account.fields.Name.isAccessible()){
eachAccount = [SELECT Id, Name, Address
FROM Account
WHERE Id =: accountId];
}
return eachAccount;
} - Then import the apex function in the LWC component.
import getAccountData from "@salesforce/apex/RuleDetails.getAccountDetails";
- Get the account id from the record page.
@wire(CurrentPageReference)
pageRef;
@track accountRecordId;
if (this.pageRef.type == 'standard__recordPage') {
this.accountRecordId = this.pageRef.attributes.recordId;
} - Call the apex function inside the connectedCallback and pass the account id to it to fetch the account details.
@track producersList;
connectedCallback() {
let producerLists = [];
getAccountData
({
accountId: this.accountRecordId
})
.then((result) => {
producerLists.push({
'recId': this.accountRecordId,
'recName': result.Name,
'address': result.Address
});
this.producersList = producerLists;
})
.catch((error) => {
console.log('In connected call back error....');
this.error = error;
console.log('Error is', this.error);
});
}