Hello guys, In this post, I will show you, how you can refresh lightning datatable after executing standard edit event in lightning web component(LWC). so let's begin.

Refresh datatable after edit record in lightning web component

Use Case: When you try to edit record with NavigationMixin Edit event, record edited successfully but lightning datatable not refreshed, the datatable should get auto-refreshed without having refresh/reload the complete page. How can we achieve this?

Now as we have understood the requirement, let's see how can we achieve this. We have to go through the following points to accomplish this task.

1) Create a Platform Event.

2) Created an Apex Trigger to create the platform event record.

3) Create an Apex class to get account records.

4) Create a LWC to implement this requirement.  

Note: Here we use platform event because like aura we don't have any equivalent force:refreshView event in LWC. So this will allow us to refresh the lightning datatable in real time whenever standard action performed like edit of a record.

1. Create a Platform Event

Navigate to Setup | Platform Events and create platform event named RefreshDataTable. Also create a custom field Record Id. Once you are done, the platform event should look like below image.


2. Created an Apex Trigger to create the platform event record

Create an apex trigger named AccountTrigger on account object to create the platform event record.

 trigger AccountTrigger on Account (after insert, after update) {
if(trigger.isAfter){
if(trigger.isInsert || trigger.isUpdate){
List<RefreshDataTable__e> refreshDataTableEvents = new List<RefreshDataTable__e>();
for (Account account : Trigger.new) {
refreshDataTableEvents.add(new RefreshDataTable__e(
RecordId__c = account.Id
));
}
EventBus.publish(refreshDataTableEvents);
}
}
}

3. Create an Apex class to get account records

Create an apex class named RefreshDataTableHandler to pull the account records for datatable.

 public class RefreshDataTableHandler {
@AuraEnabled(cacheable = true)
public static List<Account> getAccounts(){
return [SELECT Id, Name,AccountNumber,Type,Phone FROM Account ORDER BY Name];
}
}

4. Create a LWC to implement this requirement

Create a lightning web component named RefreshDataTableLWC to make the all things working together.

RefreshDataTableLWC.html

 <template>
<lightning-card title="Refresh Lightning Datatable after Edit Record" icon-name="utility:edit_form"> <br/>
<div style="width: auto;">
<template if:true={data}>
<lightning-datatable data={data} columns={columns} key-field="id" hide-checkbox-column="true"
onrowaction={handleRowActions}></lightning-datatable>
</template>
</div>
</lightning-card>
</template>
RefreshDataTableLWC.js
 import { LightningElement, track, wire } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { refreshApex } from '@salesforce/apex';
import getAccounts from '@salesforce/apex/RefreshDataTableHandler.getAccounts';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';

//define row actions
const actions = [
{ label: 'Edit', name: 'edit' }
];

//define datatable columns with row actions
const columns = [
{ label: 'Name', fieldName: 'Name' },
{ label: 'AccountNumber', fieldName: 'AccountNumber' },
{ label: 'Type', fieldName: 'Type' },
{ label: 'Phone', fieldName: 'Phone', type: 'Phone' },
{
type: 'action',
typeAttributes: {
rowActions: actions,
menuAlignment: 'right'
}
}
];

export default class RefreshDataTableLWC extends NavigationMixin(LightningElement) {
@track data;
@track columns = columns;
recordId;
refreshTable;
error;
subscription = {};
CHANNEL_NAME = '/event/RefreshDataTable__e';

connectedCallback() {
subscribe(this.CHANNEL_NAME, -1, this.handleEvent).then(response => {
console.log('Successfully subscribed to channel');
this.subscription = response;
});

onError(error => {
console.error('Received error from server: ', error);
});
}

handleEvent = event => {
const refreshRecordEvent = event.data.payload;
if (refreshRecordEvent.RecordId__c === this.recordId) {
this.recordId = '';
return refreshApex(this.refreshTable);
}
}

disconnectedCallback() {
unsubscribe(this.subscription, () => {
console.log('Successfully unsubscribed');
});
}

// retrieving the accounts using wire service
@wire(getAccounts)
accounts(result) {
this.refreshTable = result;
if (result.data) {
this.data = result.data;
this.error = undefined;

} else if (result.error) {
this.error = result.error;
this.data = undefined;
}
}

handleRowActions(event) {
const actionName = event.detail.action.name;
const row = event.detail.row;
this.recordId = row.Id;
switch (actionName) {
case 'edit':
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: row.Id,
objectApiName: 'Account',
actionName: 'edit'
}
});
break;
}
}
}
RefreshDataTableLWC.js-meta.xml
 <?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>RefreshDataTableLWC</masterLabel>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output: To see the output of this LWC please add it on salesforce home page or any record details page. Don't use Lightning app to preview the component because standard (NavigationMixin) event is not working in lightning app.

Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.

Happy Coding
Thank you.