-
Due to how proxies work I can only set a state as a context if it is an object. I cannot properly set the state directly as a context object. This seems very strange coming from react where you could just set a state as a context. Am i supposed to set some sort of getter that I am not aware of or is this just how proxies and reactivity work in svelte? for instance myState = $state(null) I cannot use this is deeper components, doesnt update properly and the data is not usable when it is updated? myState =({data:null}) deepState = getContext("myState") Then it works fine if i access deepState.data Any one know why you cannot directly set a state in a context or if there is another way to do this? Here is a REPL which shows this issue: REPL LINK |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 9 replies
-
This is how JS and Svelte contexts work, there is no way around this. (React executes the same component code over and over again when things change, this is not the case in Svelte.) |
Beta Was this translation helpful? Give feedback.
It's just about references and values in JS.
A property is a reference, accessing it gets the current value the property points to1.
If you have a variable that just contains a primitive like a number, passing that around does not transfer the variable, it transfers the value only.
So if you have...
...you are only passing
0
, the value ofthing
, not the variable/state itself. The signal is only triggered once when getting the value before setting the context.If you do this instead...
...you are passing a function that captures and references the state. Only calling the function the…