LWC refresh every time tab is clicked

lightning-web-componentsrefresh

I have a requirement that says "every" time a user clicks back to a tab that shows my LWC that it is updated. So this LWC is a custom listview. The user can click away from the LWC (NavigationMixin) and make changes that should change the listview. Currently, there has to be a page refresh.

I'm working on using Platform Events to update the listview LWC when relevant changes are made. I think this will work, but is there a better way? Anyone know how to trigger an update "every" time when the tab is clicked to return to the listview LWC. Something like a connectedCallback method that fires when the tab is clicked.

Best Answer

Editing this answer as per discussion in the comments section.

It is not directly possible to refresh LWC tab. It can be achieved by wrapping LWC inside aura component as below :

1 Create a aura component which renders the desired LWC using <aura:if> and use it as the tab.

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome">
<aura:attribute name="isLwcVisible" type="Boolean" default="true"/>            
<aura:if isTrue="{!v.isLwcVisible}">         
   <c:myLwc />         
</aura:if> 
</aura:component>

2 For detecting navigation away from the tab , handle aura:locationChange event as below :

<aura:handler event="aura:locationChange" action="{!handleLocationChange}"/>

here , handleLocationChange will just toggle the property in aura:if which will cause the LWC to rerender.

({
    handleLocationChange: function(component, event, helper) {
        var isLwcVisible = component.get("v. isLwcVisible");
        if (isLwcVisible) {
            component.set("v. isLwcVisible", false);
        } else {
            component.set("v. isLwcVisible", true);
        }
    },
})

Special credits to @mackmama for this.

Related Topic