LWC: cache refresh across different components? advanced technicies for cache management

cachelightning-web-componentslwc-wire-adapter

Let's say we have 2 LWC components:

  1. createOpportunity component, which uses Apex to create an Opportunity.
  2. opportunitiesList which uses @wire to get the list of Opportunities for a particular Account.
    (sample code can be found down below)

If I use createOpportunity and then navigate to another page that has opportunitiesList it won't have the latest created Opportunity.

I want to use @wire to improve performance in opportunitiesList, but I wasn't able to find a reliable solution to refresh cache across 2 components.

I tried storing information about which methods cache are invalidated in session storage and then trying to refreshApex at the start of the component, but it also seems suboptimal.

The only solution so far is to just remove @AuraEnable(Cacheable=true) and make the code imperative, but it's also an option that I don't like.

Hopefully, someone figured a way how to deal with this situation.

// createOpportunity
import { LightningElement } from "lwc";
import createOpportunity from '@salesforce/apex/OpportunityController.createOpportunity';

export default class CreateOpportunity extends LightningElement {

  async handleSave() {
    await createOpportunity({/*some info */});
  }
}
// opportunitiesList
import { LightningElement, wire, api } from "lwc";
import getOpportunities from '@salesforce/apex/OpportunityController.getOpportunities';

export default class OpportunitiesList extends LightningElement {

  @api recordId;
  
  @wire(getOpportunities, {recordId: '$recordId'})
  opportunities;
}

Best Answer

I'd add the wire method on the other component:

// createOpportunity
import { LightningElement } from "lwc";
import createOpportunity from '@salesforce/apex/OpportunityController.createOpportunity';
import getOpportunities from '@salesforce/apex/OpportunityController.getOpportunities';

export default class CreateOpportunity extends LightningElement {
    @wire(getOpportunities, {recordId: '$recordId'})
    opportunities;
    recordId;

  async handleSave() {
    this.recordId = await createOpportunity({/*some info */});
    return refreshApex(this.opportunities);
  }
}

Remember, LDS shares the cache across all components, so by triggering it on one component, other components will automatically get the update.

Related Topic