Recently, a coworker of mine was developing an advanced Lightning Web Component (LWC). The component was your standard search & filter with a results list, but it had a caveat. The results list allowed you to mutate/change the ‘status’ of item. This component also removed the item from the results list, because the change of status meant that the item no longer was applicable against the filter/query.

@track searchKey;
@track statusFilter;

@wire(searchAndFilterObjects, { searchKey: '$searchKey', status: '$statusFilter' })
results;

changeStatus(status) {
    // change the status of the item here, use updateRecord to update it.
    // refreshApex.
}

At first, the component seemed to work flawlessly. But upon executing the previous search & filter again, the item whose status was changed appeared again in the results (back from the dead!). A little bit of debugging quickly showed this was due to the caching mechanisms provided by the Lightning Data Service (LDS).

While we could of ditched the LDS all together, we would of lost all the benefits provided by it ,and lost some time refactoring a decent chunk of code. After giving it some thought, I had a hacky solution. By addjng a simple “counter” that passed in as a argument to our Apex method/controller, we could force the LDS to dump the cache and requery our source of truth!

@track searchKey;
@track statusFilter;
@track counter;

@wire(searchAndFilterObjects, { searchKey: '$searchKey', status: '$statusFilter', counter: '$counter' })
results;

changeStatus(status) {
    // change the status of the item here, use updateRecord to update it or another method.
    this.counter++;
}

Note – You only need to @track the counter if you don’t remove the mutated item from the list yourself manually. If you handle the removal, you can simply increment it, and then next time your query changes it will still force an uncached result set.

Some may ask, why didn’t you try refreshApex()?. While this is the native, “official” way of busting the cache, it is limited to only refreshing the cache for your wired results current query. The cache is not busted for past queries, so repeating one of those can result in a record coming back from the dead.

If this post helped you, or you have other ways of solving this problem, leave a comment!