Chaining LWC Wire methods

There are a few articles on the internet that present a solution to this problem. So, it is a refresher for some while eye opener for others. I will start with the usual steps and then the key aspect especially for the getRecords wire method which has a very specific syntax and it can be easily missed if not paid attention to.

The Usual

  • Declare a dynamic / reactive property
  • Set the dynamic/reactive property in the first wire method
  • Use the property in the getRecords
    • Conceptually the reactive property change shall trigger the wire method using this property

Exceptional

  • If the second method uses an array parameter for e.g. getRecords uses recordIds as an array of parameters, putting it using the dynamic representation with ‘$’ prefix will not work.
  • Revisit the dynamic/reactive property and represent it as an array
  • In the first wire method set the property and push the value into the array property. This will trigger the second wire method.

The Secret Sauce

  • Here is the working example
wireObj = [];
@track myRecordIds=[];
@wire(CurrentPageReference)
getPageReferenceParameters(currentPageReference) {
   if (currentPageReference && !this.myRecordIds) {
        this.myRecordIds= currentPageReference.state.recIds.split(',') || null;
        this.wireObj.push({recordIds: this.myRecordIds, fields: FIELDS});            
   }
}

@wire(getRecords, {records: '$wireObj' })
    wiredRecords({ error, data }) {
        if (data) {
            console.log('data : '+ JSON.stringify(data));
            // handle the data received;
        } else if (error) {
            console.log('error : '+ error);
            this.myRecordIds= null;
        }
    }

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *