Can I mutate $state within a callback? #10683
-
Svelte 5 + Sveltekit 2 Here is a minimal reproducible example: Svelte REPL <script>
class Counter {
count = $state(0);
constructor() {
setInterval(() => {
this.count = Math.floor(Math.random() * 100);
console.log('[CLASS]', this.count);
}, 2000);
}
}
let { count } = new Counter();
function logCount() {
console.log('[COMPONENT]', count);
}
</script>
<button onclick={logCount}> Log Count </button>
<br /><br />
<div>Count: {count}</div> In this example I'm trying to update state within a For more context: My actual use case is tying Is there a clean~ish workaround in the mean time? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The issue is destructuring in |
Beta Was this translation helpful? Give feedback.
The issue is destructuring in
let { count } = new Counter();
, changing it tolet counter = new Counter();
and then usingcounter.count
works as expected.