[SalesForce] Process results from two different @wire methods after the @wires are finished

I have two different @wire methods that are calling Apex methods to get different results from two different objects.

After this information has been retrieved by each @wire respectively, I'd like to afterwards compare the results and set a few other attributes on the page.

How do I achieve this? Should I use connectedCallback() or renderedCallback() or neither?

Is there a better way to do multiple Apex method calls then process them afterwards within the JS when the component loads?

I'm hoping there's a graceful way to accomplish this in LWC without having to chain Promises, or having to handle all of this within a single Apex method call.

Best Answer

Option 1: use wire handlers. Instead of writing an Attribute name, you can write a function, and store the data in attributes, then call a common function when both results are available.


Example

attr1;
attr2;
@wire(getAttr1, {})
attr1result({data,error}) {
  if(data) {
    this.attr1 = data;
    if(this.attr1 && this.attr2) {
      this.doProcessing();
    }
  } // ... errors ... //
}
@wire(getAttr2, {})
attr2result({data,error}) {
  if(data) {
    this.attr2 = data;
    if(this.attr1 && this.attr2) {
      this.doProcessing();
    }
  } // ... errors ... //
}
doProcessing() {
  // do something with attr1 and attr2 //
}

Option 2: Use a promise chain. When calling them in order, keep in mind that this will cause a minor performance penalty.


connectedCallback() {
  getAttr1({}).then(result => {
    this.attr1 = result;
    return getAttr2({})
  }).then(result => {
    this.attr2 = result;
  }).finally(()=>this.doProcessing());
}
Related Topic