From 11dbd6a0af4370ffdd83ab43db68ecb4f6e6113b Mon Sep 17 00:00:00 2001 From: Simon Holthausen Date: Fri, 15 Nov 2024 14:11:39 +0100 Subject: [PATCH] fix; explain destructuring gotcha --- documentation/docs/02-runes/02-$state.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/documentation/docs/02-runes/02-$state.md b/documentation/docs/02-runes/02-$state.md index d948d62464..5e72db6c37 100644 --- a/documentation/docs/02-runes/02-$state.md +++ b/documentation/docs/02-runes/02-$state.md @@ -259,6 +259,7 @@ count.current = 1; // $effect logs 1 ``` ```js +// @errors: 7006 /// file: class.svelte.js function logger(counter) { $effect(() => console.log(counter.count)); @@ -273,6 +274,28 @@ logger(counter); // $effect logs 0 counter.increment(); // $effect logs 1 ``` +For the same reasons, you should not destructure reactive objects, because that means their value is read at that point in time, and not updated anymore from inside whatever created it. + +```js +// @errors: 7006 +class Counter { + count = $state(0); + increment = () => { this.count++; } +} + +// don't do this +let { count, increment } = new Counter(); +count; // 0 +increment(); +count; // still 0 + +// do this instead +let counter = new Counter(); +counter.count; // 0 +counter.increment(); +counter.count; // 1 +``` + ## `$state.snapshot` To take a static snapshot of a deeply reactive `$state` proxy, use `$state.snapshot`: