Patterns for 2-way reactivity on deeply nested objects? #14338
colecrouter
started this conversation in
General
Replies: 1 comment 1 reply
-
I would probably create the class instances directly, not on |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
This is more of a discussion than a cry for help. Amongst all the Svelte 5 tutorials online, I haven't seen much in terms of handling 2-way reactivity. I'm curious about others' takes on this problem.
Let's imagine we're trying to make a contacts app. We have data like this:
Maybe we have something like this:
Ok, what if we wanted to wrap our raw data in classes? How would you go about doing it?
Getter/Setter Only
Problem 1: Getter/Setter Foot-Gun
Look at the
phoneNumbers
getter. It seems like this is because index access triggers the getter, but not the setter (correct me if I'm wrong). If you work around this, you'll likely end up with a race condition.Problem 2: Unnecessary Class Creation
Obviously, returning new objects inside a getter isn't the best solution, as every call creates a distinct instance of that class. Not to mention, it only works as long as the resulting objects don't contain any state.
Using
$derived
for SubclassesThis seems to work well, if it fits your use case (aka you don't ever need to reassign it externally).
This solves problem 2 quite elegantly, but I haven't played around much with it. By avoiding using a getter, our
User
instance is "cached" until eitherthis.raw
orthis.i
is updated.Using
$state
Inside SubclassesIs it possible to avoid recreation of classes entirely? I haven't experimented with this much yet.
Please share your thoughts on any & all of this!
Beta Was this translation helpful? Give feedback.
All reactions