Hello friends, in this chapter we will fetch cakes using wire service in Lightning Web Component
ProductManager.apxc
- To get bakery data, the component wires an Apex method “findProduct”. The Apex method makes a SOQL query that returns a list of contacts.
- Method must be static, and global or public. The method must be decorated with @AuraEnabled(cacheable=true).
public with sharing class ProductManager {
@AuraEnabled(cacheable=true)
public static list<Bakery__c> findProduct(string searchKey){
String key = '%' + searchKey + '%';
list<Bakery__c> productList = [SELECT Id, Name,Description__c,url__c,Price__c FROM Bakery__c WHERE Name LIKE :key];
System.debug(searchKey);
System.debug(productList);
return productList;
}
}
productDisplay.js
- The component’s JavaScript code imports the Apex method “findProduct” and invokes it through the wire service.
- The wire service either gets the list of cakes to the getmyProducts.data property, or returns an error to the getmyProducts.error property.
import { LightningElement, wire } from 'lwc';
import findProduct from '@salesforce/apex/ProductManager.findProduct';
export default class ProductMasterDisplay extends LightningElement {
searchKey = '';
@wire(findProduct, { searchKey: '$searchKey' })
getmyProducts;
changeSearchValue(event) {
const searchValue = event.target.value;
this.searchKey = searchValue;
}
}
productDisplay.html
The template uses the if:true directive to check whether the getmyProducts.data property is true. If it is, it iterates over it and renders the name of each cake.
<template>
<div class="slds-box slds-p-around_small" style="background-color: purple">
<h1 class="slds-align_absolute-center">Access Salesforce Data using Lightning Web Component</h1>
<div class="slds-size_1-of-2">
<lightning-input data-id='searchInputId' style="display: inherit"
placeholder='Search Cake'
onchange={changeSearchValue} value={searchValue}></lightning-input>
</div>
<br/>
<template if:true={getmyProducts.data}>
<div class="slds-grid slds-wrap slds-gutters">
<template for:each={getmyProducts.data} for:item="prod" for:index='itemindex'>
<div class="slds-col slds-size_1-of-4 slds-p-around_small" key={prod.Id}>
<lightning-card title={prod.Name} key={prod.Id}>
<center><img
src={prod.url__c}
alt="productimage"
/></center>
<br/>
<p class="slds-align_absolute-center">{prod.Description__c}</p>
<p class="price">Price: ${prod.Price__c}</p>
</lightning-card>
</div>
</template>
</div>
</template>
</div>
</template>
productDisplay.css
p.thicker {
font-weight: 900;
}
h1{
font-size: 50px;
color:white;
}
.price{
text-align: center;
color:red;
font-size:15px;
font-weight: bold;
}
Output

Conclusion: Learning is Fun !
Together we can learn faster !
Join LWC study group on Telegram
Subscribe to Youtube channel and blog to get latest updates
Reference
Change Wired Data after data its gets imperative