Refresh Record View in LWC

- How to Refresh Record View in LWC with two lines of code.

Refresh Record View in LWC

 

How to Refresh Record View in LWC

Let’s say that we have situation when we just finished quick action from opportunity record page. This action uses LWC component and runs apex method which depends on user input, updates data of this particular opportunity. It would be great if user can see updated record view just after action, but data on record page isn’t refreshed by default. Fortunately, there is a way how we can refresh record view in LWC component with really simple solution. Such solution you can combine for instance with lightning data table, which example you can find here.

To let user see the newest version of current record page you just need to add a few lines of code to your component. Firstly you need import built-in updateRecord method. To this, add below line of code at the top of your component.

1
import { updateRecord } from 'lightning/uiRecordApi';

Consequently you can run this function directly in any place. However we suggest to prepare some wrapper function to make your code more reusable, like this:

1
2
3
updateRecordView(recordId) {
       updateRecord({fields: { Id: recordId }});
   }

After that all you need to do is, run this method in place where or when you need to refresh your record page.

1
this.updateRecordView(this.recordId);

As you can see this methods takes one parameter which is Id, and as you can guess it is a Id of record which you want to refresh. We can assume that you already have Id of record which you updated, but if not, then you can use below api variable to get Id of record from current page. You can read more about making component aware of its record context here.

1
@api recordId;

And voila! In short that’s how you can easily refresh record view in LWC. In Aura components, you can try to use ‘e.force:refreshView’ event to update view of you record page. You can read more about this event in this place.

Resources

https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.use_record_context

https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.reference_update_record