Pages

Tuesday, April 30, 2024

Communicate Between Unrelated LWC Components- Lightning Message Service (LMS)

LMS is a publish and subscribe service that helps communicating between LWC, Aura components, and Visualforce pages. 

In this, first we have to defined channels called as messaging channel to define attributes through which we can publish information. Both the components (publisher and subscriber) needs to import this channel. Consider message channel as protocol through which information will be shared between 2 components.

In order to define messaging channel, you have create a folder named as "messageChannels" under default folder in VS code.



Now create a new file named as "enquiry_sender.messageChannel-meta.xml". You can give any name to file but make sure that it has extension as ".messageChannel-meta.xml".

In this xml file you define, lightningMessageFields and its description. These fields names will be used to used information from one component to another.


Note: 

If you are getting a validation error for the XML, then turn XML validation off.

In VS Code, click File > Preferences > Settings (Windows) or Code > Settings > Settings (macOS). Search for Validation. Select XML and uncheck Validation.

Now we have defined a message channel, lets use it to publish and subscriber message.

Publish LMS

In order to publish message using this channel, we need to import LMS and channel that we created

import { publish, MessageContext } from 'lightning/messageService';
import SEND_ENQUIRY_CHANNEL from '@salesforce/messageChannel/Enquiry_Sender__c';

Use below syntax to publish the LMS:

    @wire(MessageContext)
    messageContext;
    const payload = {
            email: 'sk@gmail.com',
            phone: '0123456789'
          };
          console.log('***payload:'+JSON.stringify(payload));
          publish(this.messageContext, SEND_ENQUIRY_CHANNEL, payload);


Subscribe LMS

In order to subscribe LMS, subscribing also need to import LMS and channel that we have been created for communication.

import { subscribe, MessageContext } from 'lightning/messageService';
import SEND_ENQUIRY_CHANNEL from '@salesforce/messageChannel/Enquiry_Sender__c';

Use below syntax to subscribe LMS:

    @wire(MessageContext)
    messageContext;
    subscribeToLMS() {
        this.subscription = subscribe(
        this.messageContext,
        SEND_ENQUIRY_CHANNEL,
        (message) => this.handleMessage(message)
        );
    }
    handleMessage(message) {
        console.log('**recieved message:'+JSON.stringify(message));
    }

    connectedCallback() {
        this.subscribeToLMS();
    }

In this way information can be passed between 2 LWC components which are not related to each other.

I have created 2 LWC components for demo purpose to show how it works. In first LWC component (userEnquiry), we take email and phone from user and when he clicks on send button, a message is published. Now we have another LWC component (contactCheck) which will subscribe to send_enquiry__c channel. 

So whenever first component will publish message, another LWC component will display information send by first component.




Below is complete code for reference:


Note:
LMS is powerful, effective, and easy to use, but use it only if it is necessary. Firing DOM events is much more efficient and should be first preference.

Hope this will help!!

31 comments:

  1. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Investing online has been a main source of income, that's why knowledge plays a very important role in humanity, you don't need to over work yourself for money.All you need is the right information, and you could build your own wealth from the comfort of your home! Binary trading is dependent on timely signals, assets or controlled strategies which when mastered increases chance of winning up to 90%-100% with trading. It’s possible to earn $10,000 to $20,000 trading weekly-monthly in cryptocurrency(bitcoin) investment, just get in contact with Mr Bernie Doran my broker. I had almost given up on everything about binary trading and never getting my lost funds back, till i met with him, with his help and guidance now i have my lost funds back to my bank account, gained more profit and I can now trade successfully with his profitable strategies and signals! Reach out to him on Gmail ( BERNIEDORANSIGNALS@GMAIL.COM ) , or his WhatsApp : +1(424)285-0682 for inquiries










      In this, first we have to defined channels called as messaging channel to define attributes through which we can publish information. Both the components (publisher and subscriber) needs to import this channel. Consider message channel as protocol through which information will be shared between 2 components.

      Delete
  2. ASVR Engineering pioneers innovative solutions in paper plate production
    with their advanced Paper Plate Making Machines. Offering unmatched
    reliability and efficiency, their state-of-the-art equipment delivers
    high-quality paper plates, meeting diverse market demands.
    Trust ASVR Engineering for cutting-edge te chnology that enhances
    productivity and sustainability in your business operations.

    ReplyDelete

  3. Great article on communicating between unrelated LWC components using Lightning Message Service (LMS)! Your explanations on how LMS simplifies data exchange and improves efficiency were incredibly helpful.

    For more resources on well-being and lifestyle balance, feel free to visit my website, Inner Wisdom Light (https://innerwisdomlight.com/). We offer guides on fitness, yoga, meditation, and more to support your overall health and wellness.

    ReplyDelete
  4. Nice Blog. Thanks for sharing with us. Such amazing information.
    power-bi-training-in-hyderabad

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Excellent read on the
    paper plate making machine
    It's impressive how Foodmart AgroEng continues to innovate and provide high-quality machinery for the industry. The detailed breakdown of the machine's features and benefits really highlights its efficiency and cost-effectiveness. This will undoubtedly help many manufacturers in streamlining their production process. Great job, Foodmart AgroEng!

    ReplyDelete

  7. "CreativeIndustrie.in offers top-quality paper plate making machines that are efficient and easy to use. Perfect for small businesses and large-scale production, these machines ensure high-speed output with minimal maintenance. Highly recommend for anyone looking to start or expand their eco-friendly disposable product line."For More Information to Visit Our Website CREATIVEINDUSTRIE.IN

    ReplyDelete
  8. "CreativeIndustrie.in offers top-quality paper plate making machines that are efficient and easy to use. Perfect for small businesses and large-scale production, these machines ensure high-speed output with minimal maintenance. Highly recommend for anyone looking to start or expand their eco-friendly disposable product line."For More Information To Visit Our WebsiteCREATIVEINDUSTRIE

    ReplyDelete
  9. The wire nail making machine is a high-performance, automated device designed to manufacture wire nails of various shapes, sizes, and types. It takes wire rods as input and produces finished nails through a series of automated processes, including wire drawing, cutting, pointing, and heading. With advanced features such as computerized control, servo motor drive, and precision tooling, the machine ensures accurate production, minimal waste, and high output. Capable of producing up to 500 kg of nails per hour, the machine is an ideal solution for nail manufacturers and suppliers looking to increase productivity and improve product quality. For more information visit our website: CREATIVEINDUSTRIE>

    ReplyDelete
  10. The slipper making machine is a revolutionary device that automates the production of slippers, increasing efficiency and reducing labor costs. This machine can produce a wide range of slippers, from casual to formal, in various sizes and materials. It features advanced cutting, stitching, and shaping technologies that ensure precise and consistent results. With a user-friendly interface, operators can easily select designs, materials, and sizes, and the machine will produce high-quality slippers in a matter of minutes. Ideal for manufacturers, wholesalers, and retailers, this machine is a game-changer in the footwear industry, enabling mass production with minimal human intervention. For More Information To Visit Our Website CREATIVEINDUSTRIE.IN
    CREATIVEINDUSTRIE.IN

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete

  16. Carbide InsertsCarbide inserts are replaceable bit that is used in a Cutter for working on different alloys such as Cast Iron, Aluminium, Steel in CNC Machines / Lathe Machines/ Milling Machines (Computerised Numerical Controlling Machine). The main advantage of Carbide Insert is it works faster and that result in more finishing of the Components.a href="https://jaibros.com
    ">Carbide inserts

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. The automatic notebook-making machineNotebook Making Machine in Siliguri is a versatile machine that can produce a wide range of notebooks, including exercise books, composition books, and spiral-bound notebooks. It is an ideal choice for notebook manufacturers who require flexibility in their production lines.CREATIVEINDUSTRIE.IN

    ReplyDelete
  21. Armind Industries has consistently delivered top-quality industrial machinery, making them a trusted partner in our business growth. Their innovative solutions, especially the Fully Automatic Notebook Making Machine, have significantly improved our production efficiency. Exceptional customer service and reliable after-sales support set them apart in the industry. Highly recommende

    ReplyDelete
  22. TheNotebook Making Machine has revolutionized the notebook manufacturing industry by streamlining production and enhancing efficiency. With automated processes like cutting, stitching, and binding, these machines ensure consistent quality and high-speed output. Whether for educational, corporate, or personal use, the demand for notebooks remains high, making the Notebook Making Machine an essential investment for manufacturers. Companies like Armind Industries provide advanced, reliable machines that help businesses meet market demand while reducing labor costs. For any notebook manufacturer, investing in a Fully Automatic Notebook Making Machine is a smart, long-term solution to improve production efficiency and profitability.

    ReplyDelete
  23. Armind Industries is a trusted leader in the industrial machinery sector, specializing in advanced solutions like theFully Automatic Notebook Making Machine. Established in 2008, the company has been providing high-performance equipment to streamline notebook production for manufacturers. Their machines deliver precision, speed, and consistent quality, helping businesses meet growing market demands efficiently. With a strong focus on customer service, after-sales support, and competitive pricing, Armind Industries ensures that clients have the tools they need to scale their operations successfully. Whether you’re starting a new venture or upgrading existing machinery, Armind Industries is a reliable partner in manufacturing excellence.


    ReplyDelete
  24. The Fully Automatic Notebook Cutting Machine is a game-changer in the notebook manufacturing industry. It automates the cutting process, ensuring precision, speed, and consistency across large-scale production. One of the standout benefits is its ability to significantly reduce manual labor while maintaining high-quality output. This not only improves overall production efficiency but also helps manufacturers save on operational costs. For businesses looking to scale and meet the growing demand for notebooks, this machine is an invaluable asset. It's easy to operate, low maintenance, and designed for durability, making it a smart investment for any notebook manufacturer.

    ReplyDelete
  25. The fully automatic notebook making machine is a game-changer for the stationery industry. Its seamless automation of cutting, ruling, stitching, and binding processes not only boosts productivity but also ensures consistent quality. By minimizing manual labor and enhancing speed, this machine enables businesses to meet high-volume demands efficiently. Its durability and user-friendly design make it a valuable investment for both small and large-scale operations. The flexibility to handle various notebook sizes and custom designs adds to its appeal, making it a must-have for any forward-thinking printing or stationery business. Embracing this technology can significantly streamline production and reduce costs.

    ReplyDelete
  26. Notebook making machine have truly revolutionised the stationery manufacturing industry. The level of automation they offer, from paper cutting to binding, is remarkable, making the entire production process more efficient and cost-effective. These machines are a game-changer for businesses, especially those looking to scale operations. Not only do they significantly reduce labour costs, but they also ensure consistency in quality, which is crucial in mass production. Plus, with the ability to customise sizes and formats, manufacturers can easily cater to specific market demands. Overall, investing in a fully automatic notebook-making machine is a smart move for any growing stationery business.


    ReplyDelete
  27. Medivant Healthcare is a pioneer in the pharmaceutical industry, providing high-quality products reliably, efficiently, affordably, and at scale for hospitals, healthcare providers, and their patients. Founded in 2015 and based in Phoenix, Arizona, Medivant Healthcare operates two fully automated CGMP FDA-registered facilities in Arizona, that produce Single Dose liquid injectable vials and pre-filled syringes.

    https://medivanthealth.com/

    ReplyDelete