Why is dispatch event from lwc to another lwc that is not in the same DOM tree?

364    Asked by darsh_6738 in Salesforce , Asked on May 5, 2023

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?

Answered by Audrey Berry

Dispatch event from lwc to another lwc that is not in the same DOM tree because - 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.



Your Answer

Interviews

Parent Categories