In this article, I will be focusing only on calling apex using @wire. If you want to get more insight, pls refer to my previous article.
To wire an Apex method, the method must be cacheable.
To wire a cacheable Apex method, use the @wire decorator
Wired methods must be cacheable, data can come from the LDS cache or the server. To refresh the data that was cached by an Apex method, call the refreshApex function.
Way to wire apex method
There two ways to call the apex method using wire-
Wire a property
Wire a method
Syntax-
@wire(apexMethodName, { apexMethodParams }) propertyOrFunction;
apexMethodParams is optional, when apex method looks for parameter then only this is needed.
Refer this link for how to configure the Salesforce dx for web components
Wire a property without parameters
Create apex Class-
public with sharing class Blog_AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts() {
List<Account> lstAcc=[Select Id,
Name,
AnnualRevenue,
Industry
from Account with SECURITY_ENFORCED];
return lstAcc;
}
}
Create Blog_Accountlists.html-
<template>
<lightning-card>
<template if:true={accounts.data}>
<lightning-datatable
key-field="Id"
data={accounts.data}
columns={columns}
>
</lightning-datatable>
</template>
</lightning-card>
</template>
Create Blog_Accountlists.js-
import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/Blog_AccountController.getAccounts';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import REVENUE_FIELD from '@salesforce/schema/Account.AnnualRevenue';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
const COLUMNS =[
{ label: 'Account Name', fieldName: NAME_FIELD.fieldApiName, type: 'text' },
{ label: 'Annual Revenue', fieldName: REVENUE_FIELD.fieldApiName, type: 'currency' },
{ label: 'Industry', fieldName: INDUSTRY_FIELD.fieldApiName, type: 'text' }
];
export default class Blog_Accountlists extends LightningElement {
columns=COLUMNS;
@wire(getAccounts)accounts;
}
Wire a property without parameters
Create an Apex class with parameters
public with sharing class Blog_ContactSearch {
@AuraEnabled(cacheable=true)
public static List<Contact> findContacts(String searchKey){
String key = '%' + searchKey + '%';
return [SELECT Id,
Name,
Title,
Phone,
FROM Contact WHERE Name LIKE :key
WITH SECURITY_ENFORCED
LIMIT 10];
}
}
Create blog_apexWireMethodWithParams.html
<template>
<lightning-card>
<template if:true={accounts.data}>
<lightning-datatable
key-field="Id"
data={accounts.data}
columns={columns}
>
</lightning-datatable>
</template>
</lightning-card>
</template>
No comments:
Post a Comment