LWC Arrays and Objects not updating on UI

Author: Bruce Tollefson Published: October 26, 2022; Modified: October 26, 2022
code

When using updating an array or object and trying to have it show on the UI you may have noticed it not updating. Changing an LWC or Object value won’t trigger an update through the UI. If you are looping through a list or referencing an object and waiting for a change this may pertain to you.

I will create a very rough LWC with no styling that will just be used as a demo:

Array and Object LWC HTML

<template> <div class="slds-card"> {arr} <br> {objString} <br> <lightning-button label="Update Array and Object" onclick={handleClick}></lightning-button> </div>

Array and Object LWC JS

import { LightningElement } from 'lwc'; export default class ArrayAndObjectTester extends LightningElement { obj = { "Hello":"World" }; arr = ["Hello", "World"]; handleClick(){ this.obj["Second"] = "Hello"; this.arr.push("Second Hello"); console.log(JSON.stringify(this.obj)); console.log(JSON.stringify(this.arr)); } get objString(){ let obj = JSON.stringify(this.obj); return obj; } }

The component will look like so:

After clicking the button you will notice nothing happens. However if you look in the console log you will see:

{"Hello":"World","Second":"Hello"} ["Hello","World","Second Hello"]

As we can see the lightning web component object and array updated but the update did not show in the component. If you were using a template if:true or looping through the array it wouldn’t work. In order for the component to register the change to the array or object you can use the spread operator to get the changes to work / show. As an example if we change the above js file to:

import { LightningElement } from 'lwc'; export default class ArrayAndObjectTester extends LightningElement { obj = { "Hello":"World" }; arr = ["Hello", "World"]; handleClick(){ this.obj["Second"] = "Hello"; this.arr.push("Second Hello"); console.log(JSON.stringify(this.obj)); console.log(JSON.stringify(this.arr)); this.obj={...this.obj}; this.arr=[...this.arr]; } get objString(){ let obj = JSON.stringify(this.obj); return obj; } }

Deploy the changes and click the button we will see the changes in the UI:

Leave a Reply

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