Lightning web component listen to Aura Events [duplicate]

I have a Lightning Record Page which uses multiple components, some are LWC, some are Aura components.
I am trying to figure out a way to make sure they all refresh nicely.
For the Aura components, I use the standard $A.get('e.force:refreshView').fire();
For the LWCs, I am using fireEvent(this.pageRef, 'refresh', this.name); imported from the pubsub component, which is available in the LWC recipies found Here

My question is this, how do I add an event listener to the LWC which is listening for an Aura event (specifically force:refreshView) to ensure that LWC logic can be executed when events are dispatched from aura components.
I have tried the following:

constructor() {
    super();
    this.addEventListener('force:refreshView', this.handleRefresh.bind(this));
  }
handleRefresh() {
   //do some stuff        
}

and I have also tried this:

 connectedCallback() {
    registerListener('force:refreshView', this.handleRefresh, this);       
}

There has to be a way for a lighting web component to know when an aura event is fired…

Edit: this question is not a duplicate of This Question. The other question is asking about how to call the refresh from a Lightning Web Component, my question is how do we listen for events dispatched from Aura components.

Answer

Yes you can, it requires what I’ve coined as brokering. It requires an Aura wrapper to handle (i.e. register the event listener) and then deal with brokering it down to an embedded child-LWC which is itself pub-subbed to the LWCs you wish to broker to.

In short, it’s complicated, rough, and not ideal. But, if you have a lot of aura components you may need to do it.

I have covered this in a somewhat related (LWC to Aura) answer here but the design pattern is the same for (Aura to LWC) since you just pubsub the other way.

Just to be clear, I am currently doing this in production right now, this is not theoretical:

MessageBrokerAura.cmp

<aura:component implements="flexipage:availableForRecordHomeforce:hasRecordId">
  <aura:handler event="force:refreshView" action="{! c.handleForceRefreshViewForLWC }"/>
  <c:messageBrokerLWC aura:id="messageBroker"></c:messageBrokerLWC>
</aura:component>

MessageBrokerAuraController.js

handleForceRefreshViewForLWC: function(component, event, helper) {
  component.find("messageBroker").forceRefreshInitiated();
},

messageBrokerLWC.js

@api
forceRefreshInitiated() {
  fireEvent(this.pageRef, 'forceRefresh'); // your LWCs pubsub to this channel
}

Attribution
Source : Link , Question Author : Mitch Spano , Answer Author : tsalb

Leave a Comment