1

I have a lwc that dispatches an event to be received by another lwc that's not in the same DOM tree.

This is my child lwc block of code:

this.dispatchEvent(new CustomEvent('newfilesuccess'));

And this is my listener lwc (not parent):

constructor(){
  super();
  this.addEventListener('newfilesuccess', this.handleFileSuccess);
}
handleFileSuccess = () => {
  console.log('success!');
}

But I can't manage to handle communication between both lwcs. How can I achieve this?

Regards,

1

1 Answer 1

3

For anything other than direct parent-to-child or child-to-parent communication, you need to use a Publish-Subscribe Pattern (this links to an Aura Trailhead). Fortunately, there's already a built-in library for this, called the Lightning Message Service. Basically, you first design a channel that your two components can subscribe to in connectedCallback, and unsubscribe from in disconnectedCallback (to free memory resources). Any component subscribed to the channel will get any notifications published through the publish function. This is interoperable between both Aura and LWC components anywhere in the same DOM, even if they are not directly related in the DOM.

4
  • Thanks! That's just what I needed!
    – molinet
    Apr 5, 2022 at 9:39
  • 1
    @molinet You're welcome!
    – sfdcfox
    Apr 5, 2022 at 9:49
  • Be aware that (as far as I can find) LMS support is still beta in digital experiences (as it has been since Spring '21). This is a concern if you need to use it in a production implementation.
    – Phil W
    Apr 5, 2022 at 11:02
  • It was GA'd in Winter '22 for Aura/LWC sites. May have to flag that document to see if it needs updating Apr 5, 2022 at 11:46

You must log in to answer this question.

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