javascript / expert
Snippet
Intercepting Dynamic Array Mutations in Svelte Actions Using JavaScript Proxies
Svelte reactive statements may miss internal mutations of arrays modified via index assignment or push calls if references remain unchanged. Wrapping target arrays in a JavaScript Proxy inside a custom action traps set operations and notifies listeners with fresh array copies.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
export function watchArrayMutation(node, { targetArray, onUpdate }) {const proxy = new Proxy(targetArray, {set(target, property, value) {target[property] = value;if (property === 'length' || !isNaN(Number(property))) {onUpdate([...target]);}return true;}});return { proxy };}
svelte
Breakdown
1
export function watchArrayMutation(node, { targetArray, onUpdate }) {
Defines a Svelte action accepting a target array and a mutation callback.
2
const proxy = new Proxy(targetArray, {
Constructs a Proxy object to trap access and write operations on the target array.
3
set(target, property, value) {
Interprets array index updates and structural mutations.
4
if (property === 'length' || !isNaN(Number(property))) {
Filters trap execution specifically for numeric index assignments or array length adjustments.
5
onUpdate([...target]);
Triggers the update callback with a shallow clone to ensure state immutability.