+ Start a Discussion
ifthikar Ahmed 1ifthikar Ahmed 1 

lightning data table not getting refreshed when a new record is create via standard Quick Action Button, pls help

Lightning Data Table issue :

i have a LWC component on Inquiry Obj (Parent) which is having look up relation with the child (Relavent Proprties).
My component will display all the child records of the parent obj with inline edit functionality.
Also i have "create relavent Proprty" standerd quick action button that craetes a New relevent Prop record.

Problem is that , when a new record is created from quick action button . my data table is not getting refreshed. data table shuld show all the values in the Db. why so 

Please help 

JavaScript : 
import { LightningElement, wire, api,track  } from 'lwc';
import getRelProp from '@salesforce/apex/selectRelPropController.getRelProp';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import updateRelProp from '@salesforce/apex/selectRelPropController.updateRelProp';
import { getRecordNotifyChange } from 'lightning/uiRecordApi';
const COLS = [
    { label: 'SL.No', 
    fieldName: "recordLink", 
    type: 'url',
    typeAttributes: { label: { fieldName: "Name" }, tooltip:"Relavent Property", target: "_blank" }
    
    },
    { label: 'Property Name',
     fieldName: 'recordLinkProp',
     type: 'url',
     typeAttributes: { label: { fieldName: "PropertyRel" }, tooltip:"Property", target: "_blank" }
    
    },
    { label: 'Price', fieldName: 'Price__c' ,  type: 'currency' },
    { label: 'Created Date', fieldName: 'CreatedDate' , type: 'date' },
    { label: 'Include this in PDF', fieldName: 'Include_This_in_PDF__c' , editable: true, type: 'boolean' }
    
    
];


export default class DatatableUpdate extends LightningElement {
    @api recordId;
    columns = COLS;
    draftValues = [];
    @track wiredPropList = [];
    error;  
    @track relList = [];
    
      @wire(getRelProp, { accId: '$recordId' })
    getRelPropList(result) { 
        this.wiredPropList = result;
     if (result.data) { 
         
        console.log(result.data.length);
      var temprelList = [];  
      for (var i = 0; i < result.data.length; i++) {  
       let tempRecord = Object.assign({}, result.data[i]); //cloning object  
       tempRecord.recordLink = "/" + tempRecord.Id;       
       tempRecord.PropertyRel =  tempRecord.Property__r.Name;
       tempRecord.recordLinkProp = "/" + tempRecord.Id;       
       temprelList.push(tempRecord); 
       console.log(temprelList) ;
      }  
      this.relList = temprelList;  
      this.error = undefined;  
     } else if (result.error) {  
      this.error = error;  
      this.relList = undefined;  
     }  
    }
     
    async handleSave(event) {
        const updatedFields = event.detail.draftValues;
        console.log("chk1" +JSON.stringify(updatedFields));
        // Prepare the record IDs for getRecordNotifyChange()
        const notifyChangeIds = updatedFields.map(row => { return { "recordId": row.Id } });
        console.log("chk2" +JSON.stringify(notifyChangeIds));
    
       // Pass edited fields to the updateContacts Apex controller
        await updateRelProp({data: updatedFields})
        .then(result => {
            console.log(JSON.stringify("Apex update result: "+ result));
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Included for PDF Generation',
                    variant: 'success'
                })
            );
    
        // Refresh LDS cache and wires
        getRecordNotifyChange(notifyChangeIds);
    
        // Display fresh data in the datatable
        refreshApex(this.wiredPropList).then(() => {
            // Clear all draft values in the datatable
            console.log();
            this.draftValues = [];
          });
    
        
       })
        .catch(error => {
         this.dispatchEvent(
              new ShowToastEvent({
                  title: 'Error updating or refreshing records',
                  message: error.body.message,
                  variant: 'error'
              })
          );
      });
       
    }
}

Component : 

<template>
    <lightning-card title="Relevant Properties" icon-name="custom:custom63">
    
       
     <div > 
        <template if:true={relList}>
            <lightning-datatable
                key-field="Id"
                data={relList}
                columns={columns}
                onsave={handleSave}
                show-row-number-column
                draft-values={draftValues}>
            </lightning-datatable>  
        </template>
        
        <template if:true={relList.error}>
            <!-- handle Apex error -->
        </template>
    </div>
        
    </lightning-card>
    </template>

User-added image

apex controller : 

public with sharing class selectRelPropController {
    
    @AuraEnabled(cacheable=true)
    public static List<Relevant_Property__c> getRelProp(String accId) {
        
        return [
            SELECT Id, Name, Property__r.Name , Property__c, Price__c , Include_This_in_PDF__c ,CreatedDate 
            FROM Relevant_Property__c
            WHERE Inquiry__c  = :accId
            WITH SECURITY_ENFORCED
        ];
    }
    
    @AuraEnabled
    public static string updateRelProp(Object data) {
        List<Relevant_Property__c> relPropRecForUpdate = (List<Relevant_Property__c>) JSON.deserialize(
            JSON.serialize(data),
            List<Relevant_Property__c>.class
        );
        try {
            system.debug('Records' +relPropRecForUpdate);
            update relPropRecForUpdate;
            return 'Success: pls click on Generate PDF Button to generate the Document';
        }
        catch (Exception e) {
            return 'The following exception has occurred: ' + e.getMessage();
        }}
}

pls helpppppppppp
ANUTEJANUTEJ (Salesforce Developers) 
Hi Ifthikar,

>> http://www.saravanansfdc.com/2020/06/how-to-use-refreshapex-to-refresh-list.html

>> https://salesforceprofs.com/refresh-record-view-in-lwc/

>> https://salesforce.stackexchange.com/questions/285022/lwc-datatable-does-not-refresh-its-view

All of the above links have an implementation of refreshing the view in the lighting web components.

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.
ifthikar Ahmed 1ifthikar Ahmed 1
@ANUTEJ Thank you for you the suggestion, yet i am not able to figure out.

It would be a great help . if you could help me fixing this
Maharajan CMaharajan C
Hi Ifthikar,

Try the platform event in LWC. 

1. Relevant_Property__c after insert trigger create the entry in Platform Event Object. Then Publish the event from platform event object using trigger.

2. Subscribe the above event in your LWC compoent then handle the refresh or call the class method again from here.

Am not tried this approach yet but try this may be you will get learning also.

https://newstechnologystuff.com/2020/08/15/platform-event-in-lightning-web-components/
https://sfwiseguys.wordpress.com/2020/08/10/lightning-communication-with-platform-events/

Thanks,
Maharajan.C
Maharajan CMaharajan C
I have tried the above things with different approaches:

Also we can use the same for handle force:refreshView Event in LWC:
(<aura:handler event="force:refreshView" action="{! c.action }"/> in LWC)

https://developer.salesforce.com/forums/ForumsMain?id=9062I000000IVvqQAG

Thanks,
Maharajan.C