Communication between unrelated components using LMS in salesforce

Communication between unrelated components in salesforce using Lightning Message Service (LMS)

LMS is a publish and subscribe service that facilitates communication between Lightning web components, Aura components, and Visualforce pages.




Step1: Create a Lightning Message Channel
Create a folder named “messageChannels” under force-app/main/default
Create a file under the "messageChannels" folder with the name <channel>.messageChannel-meta.xml

Example:

<?xml version="1.0" encoding="UTF-8" ?>

<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">

    <masterLabel>CountUpdated</masterLabel>

    <isExposed>true</isExposed>

    <description>Message Channel to pass Count updates</description>

     <lightningMessageFields>

        <fieldName>operator</fieldName>

        <description>This is the operator type of the manipulation</description>

    </lightningMessageFields>

    <lightningMessageFields>

         <fieldName>constant</fieldName>

        <description>This is the number for the manipulation</description>

     </lightningMessageFields>

</LightningMessageChannel>

Step2: Create the Publisher Component

import { LightningElement, wire } from 'lwc';

import { publish, MessageContext } from 'lightning/messageService';

import COUNT_UPDATED_CHANNEL from '@salesforce/messageChannel/Count_Updated__c';


export default class RemoteControl extends LightningElement {

  
 @wire(MessageContext)

  messageContext;


  handleIncrement() {

    // this.counter++;

    const payload = {

      operator: 'add',

      constant: 1

    };

    publish(this.messageContext, COUNT_UPDATED_CHANNEL, payload);

  }

}


Step3: Create the Subscriber Component

import { LightningElement, wire } from 'lwc';

import { subscribe, MessageContext } from 'lightning/messageService';

import COUNT_UPDATED_CHANNEL from '@salesforce/messageChannel/Count_Updated__c';


export default class Counts extends LightningElement {

  subscription = null;

  priorCount = 0;

  counter = 0;


  @wire(MessageContext)

  messageContext;


  subscribeToMessageChannel() {

    this.subscription = subscribe(

      this.messageContext,

      COUNT_UPDATED_CHANNEL,

      (message) => this.handleMessage(message)

    );

  }


  handleMessage(message) {

    this.priorCount = this.counter;

    if(message.operator == 'add') {

      this.counter += message.constant;

    }else if(message.operator == 'subtract') {

      this.counter -= message.constant;

    } else {

      this.counter *= message.constant;

    }

  }


  connectedCallback() {

    this.subscribeToMessageChannel();

  }

}

Comments

Popular posts from this blog

A - Z Guide to Using the Wire Decorator in LWC Salesforce

How to Add a Dynamic Child List to Parent in Apex Class || Trigger using map

Salesforce Custom Settings: Optimizing Your CRM for Maximum Efficiency