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}];
....{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: = [
             {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: = [
             {new value}

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s