Refresh data from @wire
Do you like fetching data for your component by @wire adapter? Are you struggling with cache and refreshing that data? Check this tip and enjoy @wire!
Refresh data from @wire
Do you like fetching data for your component by @wire adapter? Are you struggling with cache and refreshing that data? Check this tip and enjoy @wire!
import { LightningElement, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class Contacts extends LightningElement {
@wire(getContacts)
contacts;
}There’s built-in refreshApex function which clears cache, but you have to know how to use it. Here are some working examples:
import { LightningElement, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class Contacts extends LightningElement {
@wire(getContacts)
contacts;
refreshRecords() {
refreshApex(this.contacts);
}
}You can use function notation in @wire, but you have to remember to store original response:
import { LightningElement, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class Contacts extends LightningElement {
_contacts;
@wire(getContacts)
contacts(value) {
this._contacts = value;
// rest of the logic
}
refreshRecords() {
refreshApex(this._contacts);
}
}All you have to do is to call refreshRecords function at the right moment.
This example with destructuring assignment syntax won’t work:
import { LightningElement, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class Contacts extends LightningElement {
_contacts;
@wire(getContacts)
contacts({ data, error }) {
this._contacts = data;
// rest of the logic
}
refreshRecords() {
refreshApex(this._contacts);
}
}

