svelte: Setting class $state property in constructor breaks all tracking

Describe the bug

When setting a class $state property in its constructor, all the reactive tracking seems to break. $effect no longer reacts to its changes, and the value that was set in the constructor is ignored.

Reproduction

Failed to reproduce in REPL, but managed to trigger it on a fairly simple repository: https://github.com/TGlide/society-demos/blob/bug-repro/src/lib/local.svelte.ts

The only workaround I found is to wrap the try catch in a setTimeout.

Logs

No response

System Info

System:
    OS: macOS 13.4
    CPU: (8) arm64 Apple M2
    Memory: 94.63 MB / 24.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 21.6.2 - /usr/local/bin/node
    npm: 10.2.4 - /usr/local/bin/npm
    pnpm: 8.15.4 - /usr/local/bin/pnpm
    bun: 1.0.29 - ~/.bun/bin/bun
  Browsers:
    Safari: 16.5
  npmPackages:
    svelte: 5.0.0-next.158 => 5.0.0-next.158

Severity

annoyance

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 18 (18 by maintainers)

Most upvoted comments

Yes, any children of a state proxy would inherit the callback. I haven’t looked too deeply at what it would entail though (we’d need to ensure that array.push only invoked the callback once even though we’re changing the length as well as the internal ‘version’ source, and we’d need to handle the case where state-with-a-callback was assigned to a property of another state-with-a-callback)

@paoloricciuti thank you for putting up the steps and repro environment I failed to do!

What are the reproduction steps?

  • go here
  • in the preview navigate to /conta
  • add some items
  • check the console to see that the effect that should sync with the local storage is not firing whenever you add a new value
  • try to refresh the page and observe it did not sync with the local storage

Bonus:

  • uncomment the line to import a faux localStorage
  • observe that now the logs are actually firing