Refresh Cache in Lwc Using RefreshApex()
The refreshApex() is used when we call apex methods in wire. We assume that everyone knows the cache is stale. If the cache is stale, the component needs fresh data. By using the refreshApex() we fetch the latest data from the server.
Objective of the component:
By using this component it shows the object’s records in the screen. At that time we are able to create a new record from the component itself. If we implement this component without refreshApex() we cannot get the latest data on the screen.
- Create a custom object called as bank.
- Create Custom Fields in our custom object
Import the library for refreshApex,
import { refreshApex } from '@salesforce/apex';
Create a Lightning web component for insert and get data using refresh cache,
RefreshApex.html
<template>
<lightning-input type="text" variant="standard" class="name"
label="bankName"></lightning-input>
<lightning-input type="text" variant="standard" class="Branchname"
label="BranchName"></lightning-input>
<lightning-button label='Create' onclick={CreateBank}>
</lightning-button>
<div>
<lightning-card>
<template for:each={BankRec.data} for:item="Bank">
{Bank.Name}<br key={Bank.id}>
</template>
</lightning-card>
</div>
</template>
RefreshApex.js
import { LightningElement,track,wire } from 'lwc';
import CreateBankRec from '@salesforce/apex/bank.CreateBank'
import FetchBankRec from '@salesforce/apex/bank.FetchRec'
import { refreshApex } from '@salesforce/apex';
export default class Testcomponent extends LightningElement {
@track BankData;
@wire(FetchBankRec) BankRec
CreateBank(){
let BankName=this.template.querySelector('.name').value;
let BranchName=this.template.querySelector('.Branchname').value;
CreateBankRec({name:BankName,Branch:BranchName}).then(()=>{
console.log('record Created');
refreshApex(this.BankRec);
})
}
}
RefreshApex.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
<target>lightning__RecordPage</target>
</targets> </LightningComponentBundle>
After creating the component,then we create the record from the component.
Result: Below image is showing existing records.
The below image is showing the latest data from the component without refreshing the page.
Note: We don’t need to refresh the page whenever we are using the refreshApex().