[SalesForce] How to refresh wired service getRecord manually

Please note that this is not duplicate of LWC Force Refresh Wire getRecord – this question and answer specifically speaks about changes in front-end/UI and capturing that in front-end BUT LDS cannot listen to database changes to record and so we need to manually refresh LDS record cache.

Question:

According to documentation of refreshApex, if we know that record has been updated in database, we can invoke refreshApex to re-invoke and refresh the cached response of Apex method response.

But for wired service getRecord, there is no such method to manually refresh the cache and it refreshes the cache only after 30 seconds from last fetching the record ( – if invoked within or after 30 seconds). If I know that the record has been updated in the database through some backend transaction (like workflow), how can we manually refresh cache of getRecord?

Best Answer

To make refreshApex clear the client-side cache it is necessary to capture and store the entire result from the getRecord wire. In this case you cannot define your handler to accept an anonymous object with data and error properties.

You need to do something like the following. First add a private property to hold the result:

_getRecordResponse;

Then update the handling of the getRecord wire response from something like:

@wire(getRecord, {...})
receiveRecord({error, data}) {
    ...
}

to:

@wire(getRecord, {...})
receiveRecord(response) {
    this._getRecordResponse = response;
    let error = response && response.error;
    let data = response && response.data;
    ...
}

Now that you have the _getRecordResponse, you can force the record to be reloaded by calling:

refreshApex(this._getRecordResponse);
Related Topic