use class in state #15043
Answered
by
brunnerh
APerricone
asked this question in
Q&A
use class in state
#15043
-
Hi, I need help for this piece of code: <script>
// this class can not be modified
function ValueCnt() {
this.value = 0;
}
let stateClass = $state(new ValueCnt());
let stateObj = $state({value:0});
function incrementClass() {
stateClass.value += 1;
console.log(`value inside class is ${stateClass.value}`);
}
function incrementObj() {
stateObj.value += 1;
console.log(`value inside obj is ${stateObj.value}`);
}
</script>
<button onclick={incrementClass}>
increment class
</button>
<button onclick={incrementObj}>
increment obj
</button>
<p>{stateClass.value} inside class</p>
<p>{stateObj.value} inside obj</p> Here we can see that the button "increment obj" works fine and the button "increment class" doesn't... how can i fix it? I tried it on playground |
Beta Was this translation helpful? Give feedback.
Answered by
brunnerh
Jan 17, 2025
Replies: 2 comments 2 replies
-
|
Beta Was this translation helpful? Give feedback.
1 reply
-
You can wrap the object and assign a new one on change. E.g. let stateClass = $state({ counter: new ValueCnt() }); stateClass.counter.value += 1;
stateClass = { ...stateClass }; // force reactivity via new object See also this issue: |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
APerricone
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can wrap the object and assign a new one on change. E.g.
Playground
See also this issue: