Sub topic 8
Passing objects and arrays, and copying them in the child
This chapter assumes you can write a basic Lightning web component and use @api to expose a public property. You should also be comfortable with spread syntax (...) and array methods such as map and sort. Earlier chapters showed that a child must not change the values it receives. Here we apply that rule to objects and arrays, where the mistakes are harder to see.
Why objects and arrays need extra care
A string or a number is a primitive value. When a parent passes "high" to a child, the child gets its own copy of that value. Objects and arrays work differently. They are reference values, so the child receives access to the same data the parent holds, not a separate copy.
Lightning Web Components protect that shared data. A value passed through a public property is read-only in the child. If the child tries to change it, the engine blocks the change. In the browser console you will see an error like this:
Uncaught TypeError: 'set' on proxy: trap returned falsish for property '0'The exact wording varies by browser and by whether the component runs in Lightning Experience or in Lightning Web Components Open Source. The cause is the same in each: the child tried to modify data owned by the parent.
The engine enforces this with a read-only proxy. A proxy is a wrapper object that intercepts reads and writes. The child can read through it, but writes are rejected. The protection is deep, so nested objects and arrays inside the value are also read-only.
Passing an object
The parent holds an object in a field and binds it in the template. The child exposes a public property that receives it.
// taskBoard.js (parent)
import { LightningElement } from 'lwc';
export default class TaskBoard extends LightningElement {
selectedTask = {
id: 't1',
name: 'Write documentation',
priority: 'high',
owner: { name: 'Ana', team: 'Docs' }
};
}<!-- taskBoard.html (parent) -->
<template>
<c-task-detail task={selectedTask}></c-task-detail>
</template>// taskDetail.js (child)
import { LightningElement, api } from 'lwc';
export default class TaskDetail extends LightningElement {
@api task;
}<!-- taskDetail.html (child) -->
<template>
<template lwc:if={task}>
<h3>{task.name}</h3>
<p>Priority: {task.priority}</p>
<p>Owner: {task.owner.name}</p>
</template>
</template>The child reads task.name and task.owner.name without trouble. Reading is always allowed. Problems start when the child writes.
What goes wrong when the child writes
Suppose the child adds a handler that changes the received object:
// taskDetail.js (child) - this fails
import { LightningElement, api } from 'lwc';
export default class TaskDetail extends LightningElement {
@api task;
handleEscalate() {
this.task.priority = 'urgent'; // Error: the value is read-only
}
}Reassigning the whole property fails too, as an earlier chapter explained. In a child, this.task = {...} is not allowed for an @api property that the parent sets. Code in the child should treat every @api value as input only.
Arrays behave the same way. Calling push, splice, reverse or in-place sort on a received array throws an error, because each of these mutates the array.
// taskList.js (child) - these all fail on a received array
this.tasks.push({ id: 't9', name: 'New task' });
this.tasks.sort((a, b) => a.name.localeCompare(b.name));
this.tasks[0].name = 'Renamed';The last line shows that the protection reaches inside the array. Changing a property on an item is also rejected.
Copying in the child
When the child needs to change the data, it copies it first and then works on the copy. Store the copy in a private field. A private field is a class field without @api, so the parent cannot see or set it.
For a flat array, a spread copy is enough:
const copy = [...this.tasks];Spread makes a shallow copy. A shallow copy has a new outer array, but the items inside are the same objects as before. That is fine for reordering or filtering, because those operations do not touch the items. It is not enough if you change fields on an item.
For changes to items, copy each item you plan to change:
const renamed = this.tasks.map((task) =>
task.id === 't1' ? { ...task, name: 'Renamed' } : task
);Here map builds a new array. Only the matching item is replaced with a new object that has the same fields plus the new name. Unchanged items are reused, which is cheap and safe because you do not write to them.
When the data is nested and you need to change something deep, you have two options:
- Copy each level you change, using spread at every level. This is explicit and keeps the copy small.
- Make a full deep copy with
JSON.parse(JSON.stringify(value)). This is short, but it drops values that JSON cannot represent, such asundefined, functions andDateobjects (dates become strings). Use it only for plain data.
// Deep copy of plain data only
const deepCopy = JSON.parse(JSON.stringify(this.task));
deepCopy.owner.team = 'Platform';Avoid structuredClone on a received value unless you have tested it in your target environment. The read-only proxy can cause it to fail, because proxies cannot be cloned directly.
Where to copy: the setter
You could copy in every method that needs to change the data. A cleaner approach is to copy once, when the value arrives. An @api getter and setter pair lets you do this. The setter runs each time the parent assigns a new value.
// taskList.js (child)
import { LightningElement, api } from 'lwc';
export default class TaskList extends LightningElement {
_tasks = [];
@api
get tasks() {
return this._tasks;
}
set tasks(value) {
// Copy the incoming array: values from a parent are read-only in the child.
this._tasks = Array.isArray(value) ? [...value] : [];
}
handleSortByName() {
this._tasks = [...this._tasks].sort((a, b) => a.name.localeCompare(b.name));
}
}Three details matter in this code.
- The
@apidecorator goes on the getter only. Do not put it on both the getter and the setter. The engine reports an error if you decorate both. - The setter checks
Array.isArrayand falls back to an empty array. This protects the template fromundefinedor a wrong type. handleSortByNameassigns a new array to the private field. It does not callsorton the field directly. The[...this._tasks]copy keeps the original array untouched, although here the original is already a private copy and could be sorted in place. The explicit copy is a habit that stays safe if the code changes later.
Because _tasks is a field of the component, assigning a new value to it makes the template render again. That is how the sorted list appears on screen.
When the parent changes its data
The child's copy is a snapshot. If the parent later changes its own array, the child's private copy does not update by itself. What matters is how the parent changes it.
If the parent assigns a new array to the field that is bound in the template, the child's setter runs again and refreshes the copy:
// taskBoard.js (parent)
addTask(newTask) {
this.tasks = [...this.tasks, newTask]; // new array: the child's setter runs
}If the parent mutates the same array in place, the bound property still points to the same array. The child is not given a new value, so the setter does not run and the child keeps showing its old copy:
// taskBoard.js (parent)
addTask(newTask) {
this.tasks.push(newTask); // same array: the child's setter does not run
}The safe habit is that the parent replaces objects and arrays with new ones when the data changes, and the child copies them on arrival. The spread syntax makes both easy.
The parent's own data must stay consistent too. If the child copies and edits locally, the parent is not told. To send the result back, the child fires a custom event with the changed data. A later chapter covers events.
Quick reference
| Task in the child | Allowed on a received value? | Safe approach |
|---|---|---|
| Read a field or an item | Yes | Read directly |
| Assign `this.prop = ...` | No | Store in a private field |
| `push`, `splice`, `reverse` | No | `[...arr, item]` or `arr.filter(...)` |
| `sort` | No (it changes the array) | `[...arr].sort(...)` |
| Change `obj.field` | No | `{ ...obj, field: value }` |
| Change a nested field | No | Spread each level, or deep copy plain data |
Common mistakes
- Sorting a received array in place. Use
[...this.tasks].sort(...). - Copying with
const copy = this.tasks. This only creates a second name for the same read-only data. - Using a shallow copy and then editing an item's fields. The items are still read-only.
- Decorating both the getter and the setter with
@api. - Mutating the parent's array in place and expecting the child to refresh.
Exercise
A child component has @api items; and a button handler that runs this.items.reverse();. The browser console shows a read-only error. Rewrite the child so the list can be reversed, and say why the parent's array is unaffected.
Show answer
Use a getter and setter with a private field. The setter copies the array on arrival, and the handler assigns a new reversed array:
items = [];
@api
get items() {
return this.items;
}
set items(value) {
this.items = Array.isArray(value) ? [...value] : [];
}
handleReverse() {
this.items = [...this._items].reverse();
}
The original reverse() tried to change the array the parent owns, which the read-only proxy blocks. The new code reverses a copy held in the child's private field, so the parent's array is never touched.
Exercise
The parent runs this.tasks.push(newTask); and the child, which copies in its setter, does not show the new task. Why, and what is the fix?
Show answer
Pushing changes the same array in place, so the property bound to the child still holds the same array reference. The child gets no new value and its setter does not run, so its copy stays old. The fix is to assign a new array in the parent: this.tasks = [...this.tasks, newTask];.