Lightning Message Service (LMS) in LWC With Example





Let's look at how to send data using Lightning Message Service in LWC

To create a Message Channel in Salesforce, you typically follow a series of steps that involve using various tools and platforms. Here's a paraphrased version of the steps you can take to create a Message Channel:

  • Install Visual Studio Code (VS Code) on your computer if you haven't already.
  • Set up the Salesforce Extension Pack in VS Code to enable Salesforce development features.
  • Authenticate VS Code with your Salesforce Developer Org or Sandbox using the Salesforce CLI.
  • Open VS Code and create a new project or open an existing project that you want to work with.
  • Create an XML file in your project's directory to define the Message Channel. You can use a text editor within VS Code to create this file.
  • Write the necessary XML code in the file to define the Message Channel properties, such as the name, description, and platform event fields.
  • Save the XML file with a meaningful name and the ".messageChannel-meta.xml" extension to indicate its purpose.
  • Use the Salesforce CLI commands in the VS Code terminal to deploy the Message Channel metadata to the respective Salesforce org. You'll need to specify the target org and the directory where the XML file is located.
  • Monitor the deployment process in the terminal and ensure that it completes successfully.
  • Once the deployment is finished, you can verify the Message Channel's existence in the target org, either through the Salesforce user interface or by querying the metadata via the Salesforce API.
Here is the XML file used to create a MessageChannel.

Step 1: 
CloudHAK.messageChannel-meta.xml :


<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>AccountData</masterLabel>
<isExposed>true</isExposed>
<description>This is a channel which is used by LWC component to send data
</description>
    <lightningMessageFields>
        <description>This is First Name</description>
        <fieldName>firstName</fieldName>
    </lightningMessageFields>
    <lightningMessageFields>
        <description>This is Last Name</description>
        <fieldName>lastName</fieldName>
    </lightningMessageFields>
</LightningMessageChannel>


Step 2: In this step, we will create two LWC component which is not related to each other, one is the Publisher and another one is the Subscriber component.

SendData.HTML : Source Component To Send The Data to target Component.

<template>
    <lightning-card title="Data Transfer Using Message Channel for Unrelated LWC Component">
        <div class = "slds-p-around_medium slds-box">
            <lightning-input  type="text"
                               name = "fName"
                               label="Enter First Name"
                               value = {firstName}
                               onchange = {handlefirstName}>
            </lightning-input><br/>
            <lightning-input  type="text"
                               name = "lName"
                               label="Enter Last Name"
                               value = {lastName}
                               onchange = {handlelastName}>
            </lightning-input>
            <br/>
            <lightning-button variant="brand" label="send data" onclick={handleClick}>
               
            </lightning-button>
        </div>
    </lightning-card>
</template>

SendData.Js

import { LightningElement,wire ,api} from 'lwc';
import { publish, MessageContext } from "lightning/messageService";
import CLOUDHAK_CHANNEL from "@salesforce/messageChannel/CloudHAK__c";
export default class SendData extends LightningElement {

    @api firstName;
    @api lastName;

    @wire(MessageContext)
    messageContext;

    handlefirstName(event){
        this.firstName = event.target.value;
    }
    handlelastName(event){
        this.lastName = event.target.value;
    }
    handleClick(){
        const messaage = {
            firstName: this.firstName,
            lastName: this.lastName
          };
        publish(this.messageContext, CLOUDHAK_CHANNEL, messaage);  
    }

}

Target Component:

reciveData.HTML : Data received from Source Component.

<template>
    <lightning-card title="Recived Data Using Message Channel
                           for Unrelated LWC Component">
        <div class="slds-m-around_medium">
            First Name : <strong>{myfirstName}</strong><br/>
            Last Name  : <strong>{mylastName}</strong>
        </div>
    </lightning-card>
</template>

reciveData.Js : Data received from Source Component.

import { subscribe, MessageContext } from 'lightning/messageService';
import CLOUDHAK_CHANNEL from "@salesforce/messageChannel/CloudHAK__c";
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ReciveData extends LightningElement {

    subscription = null;
    @wire(MessageContext)
    messageContext;

    myfirstName = '';
    mylastName  = '';

    connectedCallback() {

        this.handleSubscribe();
    }

    handleSubscribe() {
        if (this.subscription) {
            return;
        }
        this.subscription = subscribe(this.messageContext, CLOUDHAK_CHANNEL, (message) => {
        this.myfirstName = message.firstName;
        this.mylastName = message.lastName;
        this.ShowToast('Success', 'Data Transfer Successfully', 'success', 'dismissable');
        });
    }
    ShowToast(title, message, variant, mode){
        const evt = new ShowToastEvent({
            title: title,
            message:message,
            variant: variant,
            mode: mode
        });
        this.dispatchEvent(evt);
    }
}

Output




  1. Lightning Message Service
Like our post & bookmark this blog for your future learning. 
Any suggestions and improvements are most welcome, please comment your suggestions and improvement in the comment box. 
😍😍Happy Coding Sharing is Caring 😍😍

Post a Comment

Post a Comment (0)

Previous Post Next Post