[SalesForce] LWC: NavigationMixin.Navigate not able to refresh/reload the whole page

I have a Community page called page_A and a LWC is on this page. The HTML file has these two parts where {flag} is a tracked variable in js file.

<template if:true={flag}>     
... A part ...                                                                                                 
</template>                               

<template if:false={flag}>   
... B part ...                         
</template> 

In the js file there is a @wire Apex method called "getFlag" that returns {flag} value.

@wire (getFlag)
wiredGetFlag({error,data}){
    if (data) {
        this.flag = data.flag;
    } else if (error) {

    }
} 

Suppose flag is true now and "A part" is shown. After doing something in another component in another page, I want to navigate back to "A_page" to see that flag is now turned to "false" and "B part" is shown.

this[NavigationMixin.Navigate]({
  type: 'standard__namedPage',
    attributes: {
     pageName: 'page_A',
    },
});

It turns out that after navigating back to page_A, the value would not be updated. Only if I press F5 to reload the page would the @wired function be run again so that I can see flag value turned "false".

Any idea how I can reload the page in SFDC community using NavigationMixin.Navigate without pressing F5 by hand?

Thanks.

Best Answer

Using refreshApex()

Since you are using a wired function, you can invoke refreshApex() to refresh the component's data when the component is loaded (i.e. in connectedCallback()), rather than pulling data from the cache.

Using the code that you provided, the module with the wired function would become:

// IMPORTANT - remember to import the function
import { refreshApex } from '@salesforce/apex';

...

@track flag = {};

// Introduce property to track the wired result to refresh later
wiredFlag;

@wire (getFlag)
wiredGetFlag(result){
    this.wiredFlag = result;

    // Destructure result into two variables: data and error
    const { data, error } = result;

    if (data) {
        this.flag = data.flag;
    } else if (error) {

    }
}

connectedCallback() {
    // Refresh the data on load
    if (this.wiredFlag && this.wiredFlag.data) {
        refreshApex(this.wiredFlag);
    }
}

Note: you cannot refresh data that has been fetched imperatively using refreshApex() since it was never cached, as per documentation https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.apex


If you do not need to handle the wired function error in JS, you can simplify the module:

JS

import { refreshApex } from '@salesforce/apex';

...

@wire (getflag) flag;

connectedCallback() {
    if (this.flag && this.flag.data) {
        refreshApex(this.flag);
    }
}

HTML

<template>
    <template if:true={flag.data}>{flag.data.flag}</template>
    <template if:true={flag.error}>{flag.error}</template>
</template>