I'm trying to use $effect()
to persist a class
object to localStorage
in a Svelte 5 / SvelteKit project. I'm expecting to $effect()
to fire whenever test
is modified, but it doesn't.
For a reproduction of the issue, I have the object defined in a .svelte.js
file like so:
/// module.svelte.jsclass TestClass { attribute = $state(0);}export const test = $state(new TestClass());
In my project's +layout.svelte
, I import this test
object, and I've added a button which modifies test.attribute
.
<!-- +layout.svelte --><script> import { test } from "./module.svelte.js"; $effect(() => { console.log(test); console.log($state.snapshot(test)); // neither prints anything after mounting? });</script><p> {test.attribute} </p><button onclick={() => test.attribute++}> increment<!-- expecting console.log when clicked, but nothing --></button>
From my understanding, $effect()
should see test
(which is a reactive $state()
object) as a reactive dependency, and so should run whenever test
is mutated. However, the callback only seems to run once when the DOM is mounted, and further modifications to test
do not trigger a re-run.
I'm unsure why $effect()
isn't working here as expected.
I've tried messing around with which objects are wrapped in $state()
(test
, test.attribute
, and both of them as above), but it makes no difference to what $effect()
ends up doing.
What does work is explicitly accessing test.attribute
in the $effect()
:
$effect(() => { console.log(test.attribute) // now changing `test.attribute` runs this});
However, in the context of my actual project the persisted object will have many, many attributes, so it's not viable for me to list them all explicitly inside $effect()
.
I've checked the Svelte docs on $state() and state management, but neither page was of any help.
This StackOverflow question also seemed relevant, but I can't assign test = test
since it's an import, and again, listing all its attributes isn't viable. I've also used $state.snapshot()
as was suggested there, so still unsure why that doesn't work.
I'm quite interested to understand the technical reasons behind why this doesn't work as well as how to fix it, so explanations would be really appreciated. (I imagine my understanding of Svelte reactivity has flaws?)
Reproduction in Svelte REPL: svelte.dev
(this is my first post, apologies for any missing information or context)