Skip to content

Missing reactivity when using state wrapper #14898

@autriz

Description

@autriz

Describe the bug

When creating a state wrapper with external function inside .svelte.ts file:

export function createAnotherState(value: number) {
    let state = new State(value);
	
     // does not work
    function doubleValue() {
        state.current *= 2;
    }
	
    return {
	current: state.current,
	doubleValue,
    };
}
	
class State {
    #value = $state<number>()!;
	
    constructor(value: number) {
        this.#value = value;
    }
	
    get current() {
        return this.#value;
    }
	
    set current(value: number) {
        this.#value = value;
    }
}

the function does not appear to be reactive. But when creating the same function, but inside .svelte file, reactivity is there:

<script lang="ts">
	import { createAnotherState } from "./ctx.svelte.ts";

        let ctx = createAnotherState(5);

        // works
        function doubleValue() {
            ctx.current *= 2;
        }
</script>

<div>
        <p>{ctx.current}</p>
        <button onclick={() => ctx.current = 10}>change</button>
        <button onclick={() => ctx.doubleValue()}>double 1</button>
        <button onclick={() => doubleValue()}>double 2</button>
</div>

Reproduction

https://svelte.dev/playground/9cb8fe6170194be991df1a84520548a4?version=5.16.1
There are three variants of wrapper that do the same thing. The second wrapper createAnotherState has the described issue.

Logs

No response

System Info

System:
  OS: Windows 10 10.0.19045
  CPU: (16) x64 AMD Ryzen 7 5800X 8-Core Processor
  Memory: 17.53 GB / 31.90 GB
Binaries:
  Node: 22.11.0 - C:\Program Files\nodejs\node.EXE
  npm: 10.2.3 - C:\Program Files\nodejs\npm.CMD
  pnpm: 9.10.0 - ~\AppData\Roaming\npm\pnpm.CMD
  bun: 1.1.20 - ~\.bun\bin\bun.EXE
Browsers:
  Edge: Chromium (127.0.2651.74)
  Internet Explorer: 11.0.19041.4355
npmPackages:
  svelte: ^5.0.0 => 5.16.0

Severity

blocking an upgrade

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions