Search code examples
salesforcesalesforce-lightning

LWC - How would I refresh the data of a lightning-datatable after a new record is created?


I am using the wire service along with an apex controller to initially fetch the data.

Like this: @wire (fetchAccounts)parameters.

I would like to be able to view the newly created account on the datatable as:

    <lightning-datatable 
       key-field="id"
       data={parameters.data}
       onrowaction={handleRowAction}
       row-number-offset={rowOffset}
       hide-checkbox-column="true"
       columns={columns}>
    </lightning-datatable>

What is the right approach?


Solution

  • In order to achieve this, the documentation can be found here: https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.apex#data_apex__refresh_cache.

    So that would look like this:

    
    // add this import statement
    import { refreshApex } from '@salesforce/apex';
    
    
    
        @track parameters;
        @track error;
    
        /** Wired Apex result so it can be refreshed programmatically */
        _wiredResult;
    
        @wire(fetchAccounts)
        wiredCallback(result) {
            this._wiredResult = result;
            if (result.data) {
                this.parameters = result.data;
                this.error = undefined;
            } else if (result.error) {
                this.error = result.error;
                this.parameters = undefined;
            }
        }
    
        // in order to refresh your data, execute this function:
        refreshData() {
            return refreshApex(this._wiredResult);
        }
    
    

    And change your HTML to:

    
    <lightning-datatable 
       key-field="id"
       data={parameters}
       onrowaction={handleRowAction}
       row-number-offset={rowOffset}
       hide-checkbox-column="true"
       columns={columns}>
    </lightning-datatable>
    
    
    

    If you want to read a nice sample for this, you can find that here: https://github.com/trailheadapps/lwc-recipes/blob/master/force-app/main/default/lwc/ldsDeleteRecord/ldsDeleteRecord.js