2

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;
}

1 Answer 1

1

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.

3
  • 1
    I also thought so, but during initial testing, it didn't work. I'll check again and add another comment
    – ytiq
    Mar 24, 2022 at 17:25
  • Thanks, you're right as usual) The trick is that you need to pass the same method parameters for both pages, otherwise it wouldn't refresh results
    – ytiq
    Mar 27, 2022 at 18:21
  • still don't know how to do this elegantly, because caching issues can happen in multiple places in the application.
    – ytiq
    Mar 27, 2022 at 18:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .