html code

force:refreshView (getRecordNotifyChange) within a Lightning Web Component

We’re quite fond of the Lightning UI and the Aura feature (e.force:refreshview) that allows data updates on the current Lightning page, record, or component. We missed this functionality in LWC and observed many resorting to a combination of Aura and LWC to achieve it.

However, starting Winter ’21, a new function has arrived in town!

Using it is as straightforward as what we’ve been accustomed to in Aura. You just need to import it (import { getRecordNotifyChange } from ‘lightning/uiRecordApi’;), and then call it with a list of record Ids (getRecordNotifyChange([{recordId: this.recordId}]);).

Here’s the complete sample code:

import { LightningElement, wire } from 'lwc';
import { getRecord, getRecordNotifyChange } from 'lightning/uiRecordApi';
import apexUpdateRecord from '@salesforce/apex/Controller.apexUpdateRecord';
export default class NotifyRecordChangeExample extends LightningElement {
    @api recordId;
    // Wire a record.
    @wire(getRecord, { recordId: '$recordId', fields: ... })
    async handler() {
      // Update the record via Apex.
      await apexUpdateRecord(this.recordId);
      // Notify LDS that you've changed the record outside its mechanisms.
      getRecordNotifyChange([{recordId: this.recordId}]);

This does entail one key difference: ‘force:refreshView’ used to refresh the entire page, whereas ‘getRecordNotifyChange()’ only refreshes the specific records you specify. So, if your Apex code, for example, updates the current Account along with some child Contacts, you might need to provide ‘getRecordNotifyChange()’ with all the IDs affected by your Apex method.