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

Most upvoted comments

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:

let note = $state({
  contents: 'With Runes :(',
  get lowercased() {
    return this.contents.toLowerCase();
  }
});

REPL

The class can also be simplified using $derived in the class:

class Note {
  contents = $state() as string // <- fix for TS error
  lowercased = $derived(this.contents.toLowerCase())
  constructor(contents: string) {
    this.contents = contents;
  }
}

Though the error is a bit of an annoyance in class fields. I deliberated whether I should suggest making the $state type less strict, so it won’t add undefined to 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 use as is 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_UPDATES even if the $effect isn’t self-referential:

<script>
  let text = $state('initial');
  let state = $state({});    
  $effect(() => { state.contents = text; })
</script>

text: <input bind:value={text} />
state.contents: <input bind:value={state.contents} />

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).