svelte: [Svelte 5] Runes ($effect, $derived) don't work as expected when values are nested inside an object.
Describe the bug
When the state is an object, setting up reactive dependencies within the object is cumbersome / doesn’t work as expected
Reproduction
Svelte-4 syntax - small, readable, and works as expected. REPL
<script>
let note = {contents: 'Without Runes :)', lowercased: ''};
$: note.lowercased = note.contents.toLowerCase();
</script>
<input bind:value={note.contents} />
<pre>{JSON.stringify(note, null, 2)}</pre>
Svelte-5 syntax - doesn’t work: ERR_SVELTE_TOO_MANY_UPDATES
REPL
<script>
let note = $state({contents: 'With Runes :(', lowercased: ''});
$effect(() => { note.lowercased = note.contents.toLowerCase(); })
</script>
<input bind:value={note.contents} />
<pre>{JSON.stringify(note, null, 2)}</pre>
Since $derived() can only be used as a variable declaration initializer or a class field, the following doesn’t work either
<script>
let note = $state({contents: 'With Runes :(', lowercased: ''});
note.lowercased = $derived(note.contents)
</script>
<input bind:value={note.contents} />
<pre>{JSON.stringify(note, null, 2)}</pre>
The solution recommended by @Rich-Harris is to use classes: https://www.youtube.com/watch?v=pTgIx-ucMsY&t=13986s REPL
<script lang="ts">
class Note {
contents: string = $state()
lowercased: string = $state()
constructor(contents: string) {
this.contents = contents;
this.lowercased = contents.toLowerCase();
}
toJson() {
return {
contents: this.contents,
lowercased: this.lowercased
}
}
}
let note = new Note('With Runes :(');
$effect(() => { note.lowercased = note.contents.toLowerCase(); })
</script>
<input bind:value={note.contents} />
<pre>{JSON.stringify(note.toJson(), null, 2)}</pre>
This kinda works, but
- gives a typescript error
Type 'string | undefined' is not assignable to type 'string' - is much more code for object creation and serialization
Note that explicitly typing the $state() rune by doing contents: string = $state<string>() doesn’t help either - it gives the same typescript error
The only way is to provide an initial value for the state, which seems wrong.
Logs
No response
System Info
N/A
Severity
annoyance
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 16 (11 by maintainers)
Commits related to this issue
- fix: handle ts expressions when dealing with runes related to #9639 — committed to sveltejs/svelte by dummdidumm 3 years ago
- fix: untrack reads of mutated object prevents infinite loops when mutation happens inside an effect came up in #9639 — committed to sveltejs/svelte by dummdidumm 3 years ago
- fix: handle ts expressions when dealing with runes (#9681) * fix: handle ts expressions when dealing with runes related to #9639 * docs, more tests * simplify --------- Co-authored-by:... — committed to sveltejs/svelte by dummdidumm 3 years ago
- Ensure all runes are serialized with toJSON https://github.com/sveltejs/svelte/issues/9639 — committed to exceptionless/Exceptionless by niemyjski 2 years ago
- Upgrade to Svelte 5 (#1636) * Updated to svelte5 dep * added link resources * updated client hooks * Commented out legos * removed unused code * added temp tanstack svelte5 adaptor fro... — committed to exceptionless/Exceptionless by niemyjski 2 years ago
Pulling something out of a state object and then updating the same object again in an effect is going to cause issues.
I would just not store the value redundantly in the first place:
REPL
The class can also be simplified using
$derivedin theclass:Though the error is a bit of an annoyance in class fields. I deliberated whether I should suggest making the
$statetype less strict, so it won’t addundefinedto the type if no argument is given. Would improve this case but make other places less accurate. Decided not to do so, as just moving the annotation to the end and useasis not that big of a deal, you need one anyway if no value is provided.tracking down a bug with why something wasn’t round tripped to storage due to a rune and the class missing toJson was pretty frustrating.
Just to add to this issue: you still get
ERR_SVELTE_TOO_MANY_UPDATESeven if the $effect isn’t self-referential:https://svelte-5-preview.vercel.app/#H4sIAAAAAAAAE22P0QqDMAxFfyWUgQpjvlcd7DvmHpxGCNRYbJSN0n9fuz2IsLzd3HNviFcjGXRK373ibkKl1c1adVbytkm4DY1g1G5elz5tatcvZOXacisGBQRfAg2cnHSCeUZMQp3JiqplgAR8jZ3woaggTrJPOI7YS54X0FzB_9BLP7Mgi4uZVF5BKFquy_0up7WGmtiuAk_iQW-dWbHxyQhQRuhY9Rc-IikW_5zmgUbCQWlZVgyP8AH20R9xIgEAAA==
Maybe a REPL issue, it worked locally and it appears to work in SvelteLab (try this template: https://www.sveltelab.dev/?t=five).