[SalesForce] Update child component when data in parent changes

I have a child component that receives an array as a property:

<lightning-layout-item padding="around-small">
    <c-multi-pick-list label="Product Family" options={productfamilyoptions}></c-multi-pick-list>
</lightning-layout-item>

when the parent component is loaded, the property is empty:

@track productfamilyoptions = [];

I have a @wire function that receives an array from the controller, and i am adding new values to the property productfamilyoptions:

@wire(getDataWrapper, { recordId: '$recordId', fields: '$productFields', showEval: '$showEval' })
        getData({ data, error }) {
            if (data) {
                this.assets = JSON.parse(JSON.stringify(data.assets)); //to be able to modify we dont do this.assets= data;

                var productFamilyArray = [];

                for(let i=0;i<this.assets.length;i++) {
                    if(!productFamilyArray.includes(this.assets[i].Product_Family__c)) {
                        productFamilyArray.push(this.assets[i].Product_Family__c);
                    }
                }

                for(i=0;i<productFamilyArray.length;i++) {
                    this.productfamilyoptions.push({'key':i+1,'value':productFamilyArray[i]});
                }
            } else if ( error ) {
                this.error = error;
                this.assets = undefined;
            } 
        }

After that function runs, the value of productfamilyoptions is:

[ 
   { 
      "key":1,
      "value":"Family1"
   },
   { 
      "key":2,
      "value":"Family2"
   },
   { 
      "key":3,
      "value":"Family3"
   }
]

The problem is that the child component c-multi-pick-list is not updating the values of productfamilyoptions. How do i update it?

Best Answer

Tracked properties only cause re-rendering if their value changes. The value for an array is the array itself, not the content of the array. Make sure you do something like:

this.productfamilyoptions = [].concat(this.productfamilyoptions);

after you have pushed the new options onto it. That way the tracked property will cause re-rendering.

There are other ways to deal with this, but give it a try.

Worth also noting that a component MUST NOT change the value of one of its own @api properties (in case that is what you are trying to do). Such properties are for setting by code outside the component only (generally the parent component or a lightning builder page).

Related Topic