0

I am using message channel to communicate between 2 lwc and both lwc must send and retrieve data. So i am passing value to subscriber and after that to publisher. How can i do it? Do i need to create another channel or can use same and how to wait until recieve message?

I tried and semss set value into attribute and trigger another message onchange is only way.

import { LightningElement, wire } from 'lwc';
import messageChannel from '@salesforce/messageChannel/Sample__c';
import {publish, MessageContext} from 'lightning/messageService'

    export default class Publisher extends LightningElement {
    
        @wire(MessageContext)
        messageContext;
    
        handleButtonClick() {
            let message = {messageText: 'This is a test'};
            publish(this.messageContext, messageChannel, message);
        }
      }  
import { LightningElement, wire } from 'lwc';
import messageChannel from '@salesforce/messageChannel/Sample__c';
import { subscribe, MessageContext } from 'lightning/messageService';

export default class Subscriber extends LightningElement {

    subscription = null;

    @wire(MessageContext)
    messageContext;

    connectedCallback() {
        this.handleSubscribe();
    }

    handleSubscribe() {
        if (this.subscription) {
            return;
        }
        this.subscription = subscribe(this.messageContext, messageChannel, (message) => {
            console.log(message.messageText);
        });
    }
}

1 Answer 1

1

Messaging is, by design, a one-way process; you must become both subscriber and publisher to have a two-way dialog. When you are both publisher and subscriber on the same channel, keep in mind you'll be receiving your own messages, so you must have a way to identify which messages are meant for the current component, and which are meant for the recipient component. This is certainly not an impossible task, just keep in mind you need a bit of extra metadata to keep things straight. I'd also say something about performance, yadda yadda, but it's only one extra message, so it wouldn't be a significant difference. Use one channel or two, as you prefer.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .