4. productSearch: This component consists two other components which are productSearchForm and productsList. Here user can search the product with name and the products list will show only those products.


productSearch.JS
import { LightningElement, api,wire, track } from "lwc";
// messageChannels
import {
subscribe,
unsubscribe,
MessageContext,
publish
} from "lightning/messageService";
import FILTER_CHANNEL from "@salesforce/messageChannel/productFilterChannel__c";
import CART_CHANNEL from "@salesforce/messageChannel/productSelectedChannel__c";
// apex
import getProducts from "@salesforce/apex/ProductService.getProducts";
export default class ProductSearch extends LightningElement {
searchKey = "";
subscription = null;
receivedMessage;
@track filtersData = {};
@track addCartMap = {};
@api wiredProducts;
@wire(MessageContext)
messageContext;
connectedCallback() {
this.subscribeMC();
this.findProducts();
}
findProducts() {
console.log('call findProduct');
getProducts({name: this.searchKey, filtersData: this.filtersData,productIdMap: this.addCartMap})
.then((result) => {
this.wiredProducts = result;
})
.catch((error) => {
});
}
disconnectedCallback() {
this.unsubscribeMC();
}
handleSearch(event) {
this.searchKey = event.detail.searchKey;
this.findProducts();
}
subscribeMC() {
if (this.subscription) {
return;
}
this.subscription = subscribe(
this.messageContext,
FILTER_CHANNEL,
(message) => {
console.log("message " + JSON.stringify(message));
if(message.filtersData.reset){
this.addCartMap = {};
this.wiredProducts=[];
this.findProducts();
} else {
this.filtersData = message.filtersData;
this.findProducts();
}
}
);
}
unsubscribeMC() {
unsubscribe(this.subscription);
this.subscription = null;
}
handleAddToCart(event) {
this.addCartMap[event.detail.productId]=parseInt(event.detail.selectedQuantity);
console.log('event.detail.productId'+event.detail.productId);
console.log('event.detail.selectedQuantity'+event.detail.selectedQuantity);
console.log(this.addCartMap);
this.publishChange();
}
handleRemovedFromCart(event){
if(this.addCartMap.hasOwnProperty(event.detail.productId)) {
delete this.addCartMap[event.detail.productId];
this.publishChange();
}
}
publishChange() {
const message = {
selectedData : this.addCartMap
};
publish(this.messageContext, CART_CHANNEL, message);
}
}
productSearch.html
<template>
<lightning-layout multiple-rows>
<lightning-layout-item size="12" class="slds-var-p-bottom_small">
<c-product-search-form onsearch={handleSearch}></c-product-search-form>
</lightning-layout-item>
<lightning-layout-item size="12" class="slds-var-p-bottom_small">
<c-products-list products={wiredProducts} onaddedtocart={handleAddToCart} onremovedfromcart={handleRemovedFromCart}></c-products-list>
</lightning-layout-item>
</lightning-layout>
</template>