Refresh View API in LWC: Refresh Standard Components View from Custom LWC Salesforce ⚡️


 Using new Lightning RefreshView API you will be able to refresh your Standard Components View from your Custom Lightning Web Component.

The RefreshView API and lightning/refresh module provide a standard way to refresh component data in LWC and Aura.

RefreshView API’s detailed control of refresh scope lets you create refined user experiences while maintaining backward compatibility.

RefreshView API gives you the option to update a hierarchy of components, known as a view, without reloading an entire page. This refresh ensures complete synchronization with data externally sourced by components that subscribe to the refresh event in that view. RefreshView API supports refreshes that are triggered by end users or web components. RefreshView API provides a standard mechanism for data refresh experiences in LWC components, allowing flexible control of refresh scopes.

RefreshView API can refresh data for Salesforce platform containers and custom LWC and Aura components.

Lightning Data Service supports RefreshView API.

In this example I will be creating a custom LWC datatable which will display related contacts of a particular Account on Account Detail page. Using RefreshView API we will update the contact data in our custom LWC and the same changes will be refreshed on the standard Related List of contacts.


Please check below code.

ContactController.cls

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContacts(String accId) {
        return [
            SELECT AccountId, Id, FirstName, LastName, Title, Phone, Email
            FROM Contact
            WHERE AccountId = :accId
            WITH SECURITY_ENFORCED
        ];
    }
    @AuraEnabled
    public static string updateContacts(Object data) {
    List<Contact> contactsForUpdate = (List<Contact>) JSON.deserialize(
         JSON.serialize(data),
         List<Contact>.class
    );
    try {
        update contactsForUpdate;
        return 'Success: contacts updated successfully';
    }
    catch (Exception e) {
        return 'The following exception has occurred: ' + e.getMessage();
    }
}
}


ContactListView.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<template>
  <lightning-card title="Datatable Example" icon-name="custom:custom63">
    <div class="slds-m-around_medium">
      <template if:true={contact.data}>
        <lightning-datatable
          key-field="Id"
          data={contact.data}
          columns={columns}
          onsave={handleSave}
          draft-values={draftValues}
        >
        </lightning-datatable>
      </template>
      <template if:true={contact.error}>
        <!-- handle Apex error -->
      </template>
    </div>
  </lightning-card>
</template>


ContactListView.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { LightningElement, wire, api } from "lwc";
import getContacts from "@salesforce/apex/ContactController.getContacts";
import { refreshApex } from "@salesforce/apex";
import { ShowToastEvent } from "lightning/platformShowToastEvent";
import updateContacts from "@salesforce/apex/ContactController.updateContacts";
import { RefreshEvent } from 'lightning/refresh';

const COLS = [
  { label: "First Name", fieldName: "FirstName", editable: true },
  { label: "Last Name", fieldName: "LastName", editable: true },
  { label: "Title", fieldName: "Title" },
  { label: "Phone", fieldName: "Phone", type: "phone" },
  { label: "Email", fieldName: "Email", type: "email" }
];
export default class ContactsListView extends LightningElement {
  @api recordId;
  columns = COLS;
  draftValues = [];

  @wire(getContacts, { accId: "$recordId" })
  contact;

  async handleSave(event) {
    const updatedFields = event.detail.draftValues;
    try {
      // Pass edited fields to the updateContacts Apex controller
      const result = await updateContacts({ data: updatedFields });
      this.dispatchEvent(
        new ShowToastEvent({
          title: "Success",
          message: "Contact updated",
          variant: "success"
        })
      );
        
      //Trigger RefreshView APIs
        this.dispatchEvent(new RefreshEvent());  
      // Display fresh data in the datatable
      refreshApex(this.contact).then(() => {
        // Clear all draft values in the datatable
        this.draftValues = [];
      });
    } catch (error) {
      console.log("###Error : " + JSON.stringify(error));
    }
  }
}


ContactListView.js-meta.xml

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>57.0</apiVersion>
    <isExposed>true</isExposed>
     <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>


Output


Checkout complete video tutorial below

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

Post a Comment

0 Comments