Re-render HTML when an array is modified in JS

The source of this post is this question on SFSE. Based on the question whenever a tracked array was modified in JS, the contents did not reflect back on the HTML.

The documentation mentions:

Lightning Web Components tracks changes to the internal values of these types of reactive properties:

  • Primitive values
  • Plain objects created with {}
  • Arrays created with []

So if you do something as below, where data is declared as a reactive property:

@track data = [{values}];
....
this.data.push({new values});

and that you want to re-render the HTML based on does not work.


Going back to the documentation it seems .push() does not change the values internally and that arrays created with [] will only be reactive in such cases.

So if adding the values to the array is changed to as below, it works:

this.data = [
             this.data[0], 
             {new value}
];

A more effective way to do this is to use the Spread Operator so that you don’t have to use hard coded values as [x]. So the code becomes as:

this.data = [
             ...this.data,
             {new value}
];