Skip to content

Difference in Behavior Between writable(...) and $state(...) with Classes #14411

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Tb1281 opened this issue Nov 24, 2024 · 3 comments
Closed

Comments

@Tb1281
Copy link

Tb1281 commented Nov 24, 2024

Describe the bug

It seems that writable(...) and $state(...) behave differently when used with class instances.

For example, given the following class:

class Test {
test = 0;
}

• Using writable(new Test()) makes it reactive.
• However, using $state(new Test()) does not make it reactive.

This behavior is described in the migration guide, but I wanted to confirm if this is the intended design.

If it is, should we always use writable(...) for handling reactivity with class instances?

Playground example for reference:
https://svelte.dev/playground/74b96807cf2a405984f202fe1c8a01cb?version=5.2.7

Reproduction

https://svelte.dev/playground/74b96807cf2a405984f202fe1c8a01cb?version=5.2.7

Logs

No response

System Info

All

Severity

annoyance

@brunnerh
Copy link
Member

If the class is your code, you can just make it reactive.

// has to be a in `.svelte.js`/`.svelte.ts` file or a component
class Test {
  test = $state(0);
}

Otherwise, see this issue:

... and this comment in particular.

You can of course also use a store but those have various limitations; I would generally avoid them in Svelte 5.

@dummdidumm
Copy link
Member

Closing because, yes, it is working as designed, for the reasons pointed out above.

@dummdidumm dummdidumm closed this as not planned Won't fix, can't repro, duplicate, stale Nov 24, 2024
@Tb1281
Copy link
Author

Tb1281 commented Nov 24, 2024

Yes, I can do like that. However, Class imported by other libraries are not reactive with $state(...) :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants