sveltesveltekitsvelte-5svelte-runes

$effect not triggering on property changes of class instance


I'm trying to use $effect() to persist a class object to localStorage in a Svelte 5 / SvelteKit project. I'm expecting $effect() to fire whenever the object is modified, but it doesn't.

For a reproduction of the issue, I have the object test defined in a .svelte.js file like so:

/// module.svelte.js

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

(Edit: the docs on $effect() do actually mention that mutating an object's won't trigger $effect(), which would explain the issue.)

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


Solution

  • Classes form a bit of a boundary when it comes to $state and $state.snapshot; $state wrapped around a class instance does make properties in a class reactive and $state.snapshot will not access the properties either (at least as of now). This is one of the reasons I do not really like using them and prefer just plain objects.

    You can define a toJSON method to expose the properties which will affect $state.snatshot and JSON serialization, which you presumably will need anyway if you want to store the object in localStorage (otherwise you get an empty {}).

    class TestClass {
        attribute = $state(0);
    
        toJSON() {
            return { attribute: this.attribute }
        }
    }
    

    If you don't want to list the properties manually, you could potentially use reflection along the lines of:

    toJSON() {
        const o = {};
        const descriptors = Object.getOwnPropertyDescriptors(
            TestClass.prototype
        );
        for (const [key, descriptor] of Object.entries(descriptors)) {
            if (descriptor.get == null) // $state fields have a getter
                continue;
    
            o[key] = descriptor.get.call(this);
        }
    
        return o;
    }
    

    Playground