Lightning web component to call Apex method
Things to remember before you call apex method with wire in LWC.
- Apex controller method should be static
- It should annotated with @AuraEnable(cacheable=true)
Let's check the below example component to understand more.
callApexUsingWireMethods.html
[<template><lightning-card title="Calling apex method using wire" icon-name="standard:account"><div class="slds-m-around_medium"><br/><div class="slds-border_bottom">Calling apex method with wire without params</div><template if:true={accounts.data}><ol class="slds-list_ordered"><template for:each={accounts.data} for:item="acc"><li key={acc.Id}>{acc.Name}</li></template></ol></template><br/><div class="slds-border_bottom">Calling apex method with wire with params</div><template if:true={account}><div class="slds-box slds-theme_shade"><p>Name: {account.Name}</p><p>Phone: {account.Phone}</p></div></template></div></lightning-card></template>]
callApexUsingWireMethods.js
[import { LightningElement, wire, api } from 'lwc';import getAllAccounts from '@salesforce/apex/LWC_Util.getAllAccounts';import accountDetails from '@salesforce/apex/LWC_Util.accountDetails';export default class CallApexUsingWireMethods extends LightningElement {@api recordId = '0012v00002J6XEMAA3';account;error;// wire method to property@wire(getAllAccounts)accounts;// Wire Method With Params to function@wire(accountDetails, {accountId: '$recordId'})accDetails({data, error}){if(data){this.account = data;this.error = undefined;} else if(error){this.account = undefined;this.error = error;}}}]
callApexUsingWireMethods.js-meta.xml
[<?xml version="1.0" encoding="UTF-8"?><LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"><apiVersion>48.0</apiVersion><isExposed>true</isExposed><targets><target>lightning__AppPage</target></targets></LightningComponentBundle>]
LWC_Util Apex controller:
[public with sharing class LWC_Util {@AuraEnabled(cacheable=true)public static List<Account> getAllAccounts (){return [SELECT Id, Name, AccountNumber, Phone, Industry, TypeFROM Account];}@AuraEnabled(cacheable=true)public static Account accountDetails (String accountId){return [SELECT Id, Name, AccountNumber, Phone, Industry, Type, AnnualRevenueFROM AccountWHERE Id=:accountId];}}]
also find above code in SWDC World git repo.
COMMENTS