refreshApex & deleteRecord example in LWC

Telegram logo Join our Telegram Channel

refreshApex and deleteRecord example in LWC

What is the refreshApex method?

The apex wired method result is cached at the client-side, and it is refreshed when the input parameters are changed. But sometimes we might need to refresh that data forcefully. for example when you delete a record from the list of accounts, you will want to refresh the list.


Why data is cached on the client-side?

To improve performance and quickly show the data stored at the local machine instead of doing server trips. This helps users with high latency, slow, or unreliable connections. When the data on the local cache is stale the framework refreshes it automatically.


Code Example

HTML

<template>
    <lightning-card variant="Narrow" title="Delete Opportunity from Datatable" icon-name="standard:opportunity">
        <p class="slds-p-horizontal_small">
            <lightning-datatable if:true={opportunities.data} key-field="id" data={opportunities.data}
                show-row-number-column hide-checkbox-column columns={opportunityCols} onrowaction={handleRowAction}>
            </lightning-datatable>
        </p>
    </lightning-card>
</template>

JS

import { LightningElement, wire } from "lwc";
import { deleteRecord } from 'lightning/uiRecordApi';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import getOpportunities from "@salesforce/apex/RefreshApexExampleController.getOpportunities";
const OPPORTUNITY_COLS = [
	{
		label: "Opportunity Name",
		type: "button",
		typeAttributes: { label: { fieldName: "Name" }, name: "gotoOpportunity", variant: "base" }
	},
	{
		label: "Stage",
		fieldName: "StageName"
	},
	{
		label: "Amount",
		fieldName: "Amount",
		type: "currency"
	},
	{ label: "Close Date", type: "date", fieldName: "CloseDate" },
	{ label: "Description", fieldName: "Description" },
	{
		label: "Delete",
		type: "button",
		typeAttributes: {
			label: "Delete",
			name: "deleteOpportunity",
			variant: "destructive"
		}
	}
];

export default class RefreshApexExample extends LightningElement {
	opportunityCols = OPPORTUNITY_COLS;

	@wire(getOpportunities, {})
	opportunities;

	handleRowAction(event) {
		if (event.detail.action.name === "deleteOpportunity") {
			deleteRecord(event.detail.row.Id).then(() => {
				refreshApex(this.opportunities);
				this.dispatchEvent(
					new ShowToastEvent({
						title: 'Success',
						message: "Record deleted successfully!",
						variant: 'success'
					})
				);
			}).catch((error) => {
				console.log("error, " + error);
				this.dispatchEvent(
					new ShowToastEvent({
						title: 'Error deleting record',
						message: error.body.message,
						variant: 'error'
					})
				);
			})
		}
	}
}

Meta-XML

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Apex

public with sharing class RefreshApexExampleController{
    @AuraEnabled(cacheable=true)
    public static List<Opportunity> getOpportunities(){
        return [SELECT Name, StageName, Amount, CloseDate, Description FROM Opportunity WHERE StageName = 'Closed Won' LIMIT 20];
    }
}


Output

delete-record-from-datatable-lwc

Thank you!
No comments :
Post a Comment

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com