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!

javascript
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:

javascript
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:

javascript
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:

Don't do this
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);
    }
}

Text and code were extracted from the original slide. Plain-text version of the whole catalog