Skip to content

Using refreshApex

Hello trailblazers,

Here, we will learn when do we need to use the refreshApex() function in our component. When we invoke an apex method using the wire service, we need to annotate the apex method with @AuraEnabled(cacheable=true) which caches the method results on the client. Marking a method as cacheable improves the component’s performance by quickly showing cached data from client-side storage without waiting for a server trip. If the cached data is stale, the framework retrieves the latest data from the server. The caching refresh time is the duration in seconds before an entry is refreshed in storage. The refresh time is automatically configured in the Lightning Experience and the Salesforce mobile app.

Need

Besides the standard refresh time, sometimes, you know that the cache is stale. If the cache is stale, the component needs fresh data. To query the server for updated data and refresh the cache, import and call the refreshApex(wiredProperty) function.

Example

Let’s take a scenario to get the whole idea – Suppose, in a component, we have a record edit form to create the account record and at the same time, we are displaying the list of accounts. So, when an account record is created, it should be visible in the list of accounts instantly (but it doesn’t appear …). For this purpose, we will refresh the data of the table using the refreshApex() function. See everything in action.

Let’s move to some code now.

refreshApex.html

<template>
    <lightning-card title="Demo">
        <div class="slds-p-left_large slds-p-right_large">
            <!--Record Edit Form-->
            <p>Create New Account</p>
            <lightning-record-edit-form object-api-name="Account"
                                        onsuccess={handleSuccess}>
                <lightning-messages>
                </lightning-messages>
                <lightning-input-field field-name="Name">
                </lightning-input-field>
                <lightning-button
                    class="slds-m-top_small"
                    variant="brand"
                    type="submit"
                    name="Save"
                    label="Save">
                </lightning-button>
            </lightning-record-edit-form>
                        
            <!--Lightning Datatable-->
            <p class="slds-m-top_large">All Accounts</p>
            <lightning-datatable
                key-field="id"
                data={data}
                columns={columns}
                hide-checkbox-column
                show-row-number-column>
            </lightning-datatable>
        </div>
    </lightning-card>
</template>

refreshApex.js

import { LightningElement,track, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import getAccounts from '@salesforce/apex/RefreshApexController.getAccounts';

const columns = [
    { label: 'Name', fieldName: 'Name' }
];

export default class RefreshApex extends LightningElement {
    @track data = [];
    @track columns = columns;
    accounts;

    @wire(getAccounts)
    wiredAccounts (value) {
        this.accounts = value; // track the provisioned value
        const { data, error } = value; // destructure the provisioned value
        if (data) {
            this.data = data;
        }
    }

    handleSuccess() {
        const inputFields = this.template.querySelectorAll(
            'lightning-input-field'
        );
        if (inputFields) {
            inputFields.forEach(field => {
                field.reset();
            });
        }
        const evt = new ShowToastEvent({
            title: 'Success!',
            message: "Account saved successfully.",
            variant: 'success'
        });
        this.dispatchEvent(evt);
        return refreshApex(this.accounts);
    }
}

RefreshApexController.cls

public with sharing class RefreshApexController {
   
    @AuraEnabled(cacheable=true)
    public static Account[] getAccounts(){
       return [SELECT Id,Name FROM Account];
    }
}

Published inCoding Mania

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *