December 28, 2020

How to pass data from one LWC to another in Salesforce?

Sample Code:

sample.messageChannel-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
    <masterLabel>Sample</masterLabel>
    <isExposed>true</isExposed>
    <description>This is a sample Lightning Message Channel.</description>
    <lightningMessageFields>
        <fieldName>variable1</fieldName>
        <description>Variable 1</description>
    </lightningMessageFields>
</LightningMessageChannel>

component1.html:
<template>
    <lightning-card title="Component 1">
        <lightning-button label="Publish" onclick={handleClick}></lightning-button>
    </lightning-card>
</template>

component1.js:
import { LightningElement, wire } from 'lwc';
import SAMPLEMC from "@salesforce/messageChannel/Sample__c";
import { publish, MessageContext } from 'lightning/messageService';

export default class Component1 extends LightningElement {

    @wire(MessageContext)
    messageContext;

    handleClick() {

        const message = {
            variable1: "Test"
        };
        publish( this.messageContext, SAMPLEMC, message );

    }

}

component1.js-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
    </targets>
</LightningComponentBundle>

component2.html:
<template>
    <lightning-card title="Component 2">
        Message Received is {receivedMessage}
    </lightning-card>
</template>

component2.js:
import { LightningElement, wire } from 'lwc';
import SAMPLEMC from "@salesforce/messageChannel/Sample__c";
import { subscribe, MessageContext, APPLICATION_SCOPE } from 'lightning/messageService';

export default class Component2 extends LightningElement {

    receivedMessage;
    subscription = null;

    @wire(MessageContext)
    messageContext;

    connectedCallback() {

        if ( this.subscription ) {
            return;
        }
        this.subscription = subscribe(
            this.messageContext,
            SAMPLEMC, ( message ) => {
                this.handleMessage( message );
            },
            {scope: APPLICATION_SCOPE}
        );

    }

    handleMessage( message ) {

        console.log( 'Message received is ' + JSON.stringify( message ) );
        this.receivedMessage = message ? JSON.stringify( message, null, '\t' ) : 'No Message Payload';

    }

}

component2.js-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
    </targets>
</LightningComponentBundle>

Output:


For code in GitHub, check the below link

No comments:

Post a Comment