In a separate .svelte.js
file I have
export let allQuestionsRune = $state([new ObjectWithStringProperty("hi")])
Then in a button onClick
method in some +page file I am doing
allQuestionsRune[0].stringProperty = "new string"
Then in a separate svelte component I am referencing this exact property as such:
<p>{allQuestionsRune[0].stringProperty}</p>
Expected behavior: I see a "hi" on the screen. Then I click the button, and I should see the "hi" change to "new string".
Actual Result: I see a "hi" on the screen. And that's it. The button is not updating at all. I thought this was supposed to be reactive ... I don't get what is going on. I have verified that the onClick
method is being fired correctly.
Excerpt of some svelte documentation I don't fully understand ... If $state is used with an array or a simple object, the result is a deeply reactive state proxy. ... Perhaps this is a hint ? I don't really understand this excerpt at all.
What am I missing? Why is my rune not behaving as I expect?
In a separate .svelte.js
file I have
export let allQuestionsRune = $state([new ObjectWithStringProperty("hi")])
Then in a button onClick
method in some +page file I am doing
allQuestionsRune[0].stringProperty = "new string"
Then in a separate svelte component I am referencing this exact property as such:
<p>{allQuestionsRune[0].stringProperty}</p>
Expected behavior: I see a "hi" on the screen. Then I click the button, and I should see the "hi" change to "new string".
Actual Result: I see a "hi" on the screen. And that's it. The button is not updating at all. I thought this was supposed to be reactive ... I don't get what is going on. I have verified that the onClick
method is being fired correctly.
Excerpt of some svelte documentation I don't fully understand ... If $state is used with an array or a simple object, the result is a deeply reactive state proxy. ... Perhaps this is a hint ? I don't really understand this excerpt at all.
What am I missing? Why is my rune not behaving as I expect?
Share Improve this question edited Nov 21, 2024 at 21:40 brunnerh 186k30 gold badges357 silver badges430 bronze badges asked Nov 21, 2024 at 7:46 YashYash 133 bronze badges1 Answer
Reset to default 1Class fields aren't reactive in Svelte 5. So the problem is not that the state holds and array, but that the value in the array that you try to change is an instance of a class. If it's plain JavaScript object instead, it will work.