Force refresh view in LWC

In Aura, we can do

    $A.get('e.force:refreshView').fire();

to cause standard components to update.

How can we do an equivalent in LWC because sfdx refuses to publish .js code with $A in it saying the usage is disallowed in LWC?

For now i tricked it with

eval("$A.get('e.force:refreshView').fire();");

but that is obviously less than ideal….

Answer

I was able to find an answer on the Developer Docs forum for a work-around. I was surprised how challenging it was to find a solution in the Salesforce LWC docs, so I’m not sure if this is the recommended approach, but it’s the best I’ve been able to find!

You will need to import the updateRecord method from the lightning/uiRecordApi. Then, you can call this updateRecord() function in your lwc javascript file whenever you want your detail record page (i.e. Account Detail Page) to refresh.

In the following example, I have a lwc that lives on my lightning detail page on the Account record (i.e. as a side-bar component). In the example, my lwc calls a handleClick method that imperatively calls an updateAccount() method in my Apex Controller Class. In the callback method, I update the Account Detail record using the updateRecord() function.

Import Statement:

import { updateRecord } from 'lightning/uiRecordApi';

Function:

updateRecord({ fields: { Id: this.recordId } });

Example:

import { LightningElement, api, track, wire } from 'lwc';
import { updateRecord } from 'lightning/uiRecordApi';
import updateAccount from '@salesforce/apex/ApexControllerClass.updateAccount;

export default class lightning-web-component-example extends LightningElement {

     @api recordId;

     handleClick(){

          // Call Apex Method imperatively to update Account record
          updateAccount({accountId: this.recordId})
               .this( result => {
          
                    if (result) {
                         // Refresh Account Detail Page
                         updateRecord({fields: this.recordId})
                    }

               })
     }
}

Attribution
Source : Link , Question Author : zaitsman , Answer Author : isherwood

Leave a Comment