Refresh Standard Components in LWC Salesforce

by Rijwan Mohmmed
refresh-standard-components-in-lwc-salesforce-techdicer

Hello friends, today we are going to discuss How to Refresh Standard Components in LWC Salesforce. To refresh a view, run eval("$A.get('e.force:refreshView').fire());, which reloads data for standard components. This way we will refresh the full page with related records refresh. Many users have got problems that how we can refresh the record page by the Lightning Web component. Salesforce also introduce one more method which updates related records but it is not very nice as this force:refreshView.

Also check this: How to install Salesforce Data Loader

Key Highlights :

  1. Refresh standard component
  2. Works the same like Aura Component
  3. Dynamic Data Refresh: In the dynamic world of Salesforce, real-time data is crucial. With LWC, you can now refresh standard components on your Lightning Record Pages without a full page reload.
  4. Real-Time Updates: Keep your users informed with data that’s always up-to-date, enhancing their decision-making.
  5. Seamless Interactions: No need to navigate away or manually refresh pages for new data. It’s all about efficiency and user satisfaction.
  6. Modern UI: Deliver a dynamic experience that aligns with today’s web standards.

Code :

Here we will create a Lightning Web Component(LWC) in which we will delete the contact record. And then after we will refresh the full record page. We also create Apex class to delete the contact record and return the success notification in LWC.

RefreshStandardComponentCtrl.cls:

public class RefreshStandardComponentCtrl {
    @AuraEnabled
    public static string deleteContact(String recordId){
        Contact con = [SELECT Id FROM Contact WHERE AccountId =:recordId LIMIT 1];
        delete con;
        return 'Record Delete successfully!!';
    }
}

RefreshStandardComponent.HTML:

<template>
      <!-- loader -->
    <div if:true={isLoading}>
        <lightning-spinner
            alternative-text="Loading..." variant="brand" class="slds-is-fixed">
        </lightning-spinner>
    </div>
    <!-- /loader -->
    <!--------header----->
    <div class="slds-tabs_card">
		<div class="slds-page-header">
			<div class="slds-page-header__row">
				<div class="slds-page-header__col-title">
					<div class="slds-media">
						<div class="slds-media__figure">
							<span class="slds-icon_container slds-icon-standard-opportunity">
								 <lightning-icon icon-name="standard:recipe" alternative-text="recipe" title="recipe"></lightning-icon>
                            </span>
						</div>
						<div class="slds-media__body">
							<div class="slds-page-header__name">
								<div class="slds-page-header__name-title">
									<h1>
										<span>Refresh Standard Components in LWC Salesforce</span>
										<span class="slds-page-header__title slds-truncate" title="Recently Viewed">TechDicer</span>
									</h1>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div> <br/>
    <!--/header -->


    <!-- Delete contact and refresh page -->
    <lightning-card title="Refresh Standard Component" icon-name="custom:custom17">
        <div class="slds-m-around_medium">
            <lightning-button label="Delete Contact" onclick={handleClick} variant="brand"></lightning-button>
        </div>
    </lightning-card>
    <!-- /Delete contact and refresh page -->
</template>

RefreshStandardComponent.JS:

import { LightningElement, api, track } from 'lwc';
import deleteContact from '@salesforce/apex/RefreshStandardComponentCtrl.deleteContact';
import { ShowToastEvent } from 'lightning/platformShowToastEvent'

export default class RefreshStandardComponent extends LightningElement {
    @api recordId;
    @track isLoading = false;

    handleClick() {
        this.handleIsLoading(true);
        deleteContact({ recordId: this.recordId }).then(result => {
            this.showToast('Success', result, 'Success', 'dismissable');
            this.updateRecordView();
        }).catch(error => {
            this.showToast('Error updating or refreshing records', error.body.message, 'Error', 'dismissable');
        }).finally(()=>{
            this.handleIsLoading(false);
        });
    }

    showToast(title, message, variant, mode) {
        const event = new ShowToastEvent({
            title: title,
            message: message,
            variant: variant,
            mode: mode
        });
        this.dispatchEvent(event);
    }

    //show/hide spinner
    handleIsLoading(isLoading) {
        this.isLoading = isLoading;
    }

    updateRecordView() {
       setTimeout(() => {
            eval("$A.get('e.force:refreshView').fire();");
       }, 1000); 
    }
}

Output :

refresh-standard-components-in-lwc-salesforce-example-techdicer

Reference :

  1. Salesforce
What’s your Reaction?
+1
3
+1
1
+1
0
+1
0
+1
4
+1
3

You may also like

26 comments

Monique June 7, 2022 - 3:09 pm

Thank you very much! I was looking for a way to do this in a modal lwc and it just worked only with your example.
Thank you very much!

Reply
Jeanne June 24, 2022 - 8:42 am

Hi ! Thank you so much ! I was looking for something like that !
Do you know a way to refresh only some data without refreshing all the page ? because I have a component that displays some fields when I scan the bar code of a record, and I want to show the updated data of this record. But When I refresh the view, the whole page refresh and then I have to scan the bar code again….
The goal is to get the updated data without having to scan the record twice.

Reply
Rijwan Mohmmed June 25, 2022 - 6:45 am

you can use Lightning Message Service (LMS) for that.

Reply
Chris July 14, 2022 - 10:58 am

why have you added a delay of 1000ms?

Reply
Rijwan Mohmmed July 15, 2022 - 5:20 pm

Hi Chris, you can remove the delay

Reply
Shivam Barya August 29, 2022 - 1:15 pm

Hey Rijwan,
How can we refresh the custom component whenever we delete or update any record in custom component

Reply
Rijwan Mohmmed August 30, 2022 - 9:48 am

Apex refresh , if you are using wire method for fetch records. If not then just call the method which fetching data from server

Reply
luke November 27, 2022 - 3:31 am

Hey Rijwan,
I’m getting the ‘Error updating or refreshing records’ error when I click the Delete Contact button. I copy pasted your code so it’s not a syntax problem. Any idea what could be causing it?

Reply
Rijwan Mohmmed November 27, 2022 - 3:17 pm

Can you please share your code

Reply
Luke November 27, 2022 - 6:51 pm


Refresh Standard Components in LWC Salesforce
TechDicer

Reply
Luke November 27, 2022 - 6:49 pm

public class RefreshStandardComponentCtrl {
@AuraEnabled
public static string deleteContact(String recordId){
Contact con = [SELECT Id FROM Contact WHERE AccountId =:recordId LIMIT 1];
delete con;
return ‘Record Delete successfully!!’;
}
}


Refresh Standard Components in LWC Salesforce
TechDicer

import { LightningElement, api, track } from ‘lwc’;
import deleteContact from ‘@salesforce/apex/RefreshStandardComponentCtrl.deleteContact’;
import { ShowToastEvent } from ‘lightning/platformShowToastEvent’

export default class RefreshStandardComponent extends LightningElement {
@api recordId;
@track isLoading = false;

handleClick() {
this.handleIsLoading(true);
deleteContact({ recordId: this.recordId }).then(result => {
this.showToast(‘Success’, result, ‘Success’, ‘dismissable’);
this.updateRecordView();
}).catch(error => {
this.showToast(‘Error updating or refreshing records’, error.body.message, ‘Error’, ‘dismissable’);
}).finally(()=>{
this.handleIsLoading(false);
});
}

showToast(title, message, variant, mode) {
const event = new ShowToastEvent({
title: title,
message: message,
variant: variant,
mode: mode
});
this.dispatchEvent(event);
}

//show/hide spinner
handleIsLoading(isLoading) {
this.isLoading = isLoading;
}

updateRecordView() {
setTimeout(() => {
eval(“$A.get(‘e.force:refreshView’).fire();”);
}, 1000);
}
}

Reply
Vinh Chau December 13, 2022 - 3:19 am

Hello,

What if I have custom create record component, When I click the create button it creates the record.
I want the child component to only display the result field of the created record, when the created record moves to a different status ie Completed?
What would I need to use?

Thank you.

Reply
Rijwan Mohmmed December 13, 2022 - 4:17 am

you can use parent-child event in this case

Reply
Vinh Chau December 13, 2022 - 9:48 pm

Helko Rijwan,

Thanks for the reply. I am really new to this LWC stuff, when you say parent-child event what do you mean?

Do you have an example on your site?
Thanks for the content.

Reply
Test January 25, 2023 - 1:19 pm

Hi Rijwan, I am trying to use same in my LWC component. but I am getting these error like ” Uncaught TypeError: Cannot read properties of undefined (reading ‘fire’) “

Reply
Rijwan Mohmmed January 25, 2023 - 1:44 pm

Can you please share you JS code

Reply
Ning Pariona February 27, 2023 - 9:06 pm

Hi Rijwan,

I am trying to execute the record refresh when the record name is changed, Do I need a LWC to refresh the page to do that?

Thanks

Reply
Rijwan Mohmmed February 28, 2023 - 3:23 am

Hi Ning,
Yupp you need LWC component for this.

Reply
Prasanna Daparti March 1, 2023 - 10:47 am

Hi Rijwan,
Can i use your example here, for this concept but it is refereshing full page can you please let me know

Synchronize Component Data Without a Page Refresh by Using RefreshView API (Pilot)
Whether user-driven or app-invoked, the ability to synchronize data without reloading an entire page is a key user experience requirement. The new lightning/refresh module and RefreshView API provide a standard way to refresh component data in LWC and Aura. Previously, LWC lacked a data refresh API, and Aura only supported the legacy force:refreshView, which doesn’t meet the requirements of modern web development. RefreshView API’s detailed control of refresh scope lets developers create refined user experiences while maintaining backward compatibility.

How: RefreshView API updates the data for a specific hierarchy of components, known as a view, without reloading an entire page. It synchronizes data externally sourced by components in that view and supports refreshes triggered by end users or web components. RefreshView API provides a standard mechanism for data refresh experiences in both LWC and Aura components. It allows flexible control of refresh scopes, and for Aura developers it can replace the legacy force:refreshView.

Reply
Rijwan Mohmmed March 1, 2023 - 11:12 am

Hi this refresh view which you are talking about are in pilot currently, I tried but it’s not working my org

Reply
DD March 1, 2023 - 1:03 pm

so, it means i can’t use your example, for refreshview right rijwan

How to Refresh Standard Components in LWC Salesforce. To refresh a view, run eval(“$A.get(‘e.force:refreshView’).fire());, which reloads data for standard components. This way we will refresh the full page with related records refresh. Many users have got problems that how we can refresh the record page by the Lightning Web component. Salesforce also introduce one more method which updates related records but it is not very nice as this force:refreshView.

Reply
DD March 1, 2023 - 1:05 pm

How you tried let me know, i will also try

Reply
DD March 1, 2023 - 1:00 pm

Hi Rijwan,

Can i use your example here, for this concept but it is refereshing full page can you please let me know

Synchronize Component Data Without a Page Refresh by Using RefreshView API (Pilot)
Whether user-driven or app-invoked, the ability to synchronize data without reloading an entire page is a key user experience requirement. The new lightning/refresh module and RefreshView API provide a standard way to refresh component data in LWC and Aura. Previously, LWC lacked a data refresh API, and Aura only supported the legacy force:refreshView, which doesn’t meet the requirements of modern web development. RefreshView API’s detailed control of refresh scope lets developers create refined user experiences while maintaining backward compatibility.

How: RefreshView API updates the data for a specific hierarchy of components, known as a view, without reloading an entire page. It synchronizes data externally sourced by components in that view and supports refreshes triggered by end users or web components. RefreshView API provides a standard mechanism for data refresh experiences in both LWC and Aura components. It allows flexible control of refresh scopes, and for Aura developers it can replace the legacy force:refreshView.

Reply
Hema Reddy November 21, 2023 - 10:50 am

Hi Rijwan,

I have used this code “eval(“$A.get(‘e.force:refreshView’).fire();”);” in my org, in lower environment its working fine, but in the higher environments its getting error: [$A is not defined]. I have checked every access and code comparison everything is looking good.
can you please help me with this issue

Reply
Rijwan Mohmmed November 21, 2023 - 3:22 pm Reply

Leave a Comment