javascript / expert
Snippet
Deeply Nested Reactivity via Proxy-wrapped State
While Svelte's built-in reactivity is powerful, handling deeply nested objects can sometimes lead to verbose update patterns. By wrapping the state in a recursive ES6 Proxy, we can intercept mutations at any depth and automatically trigger store updates, mimicking a more 'mutable' development experience without losing reactivity.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { writable } from 'svelte/store';function deepProxy(obj, callback) {return new Proxy(obj, {get(target, prop) {const val = target[prop];return (typeof val === 'object' && val !== null) ? deepProxy(val, callback) : val;},set(target, prop, val) {target[prop] = val;callback();return true;}});}export function reactiveObject(initial) {const store = writable(initial);const proxy = deepProxy(initial, () => store.set(initial));return { subscribe: store.subscribe, proxy };}
svelte
Breakdown
1
get(target, prop) { ... recursive ... }
Recursively wraps nested objects in Proxies to ensure deep interception.
2
callback();
Triggers the Svelte store update whenever a property is set anywhere in the object tree.