Custom setters in immutable store #1167
DaniGuardiola
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
The API docs state that it is possible to create custom setters for mutable stores, but it doesn't say anything about it for standard (immutable) stores.
I would like the ability to add setters to an immutable store for the main reason of grouping a set of related values (plus its setters) in a single object. E.g. let's imagine a Dialog component. I'd like to have a single state object (a store) with properties like
open
, and custom setters likesetOpen(value)
,show()
,hide()
,toggle()
, etc. Then you can usedialog.open
to read, anddialog.show()
to update.I don't want to use mutable stores precisely because of the drawbacks mentioned in the API docs, so I'm not talking about actual javascript property setters, just plain functions that update the store (via
setStore
) in a custom way.One idea I had for this is creating the store, and then adding the setters either manually (via
Object.assign
) or by actually adding them to the store throughsetStore
immediately after creating it (possibly passing no-op functions before that to prevent type-errors). This all would be wrapped inside e.g. acreateDialog()
function.A note is that I'd only need these setters to be defined at the top level.
It'd be nice to have an official API for this, or at least get feedback on the most idiomatic or performant way to pull this off. I suspect
Object.assign
won't break it and that it'd be the most performant way (no unnecessary reactivity), but that feels hacky, fragile, and would require a bit of typing duct taping that I'd like to avoid.The alternative (using
setStore
) seems like the "better" way to do it in that it's using the actual APIs to add properties to the store, however, it just feels plain wrong and it would add unnecessary overhead... plus callingsetStore
from a property in a store feels kinda gross.Thoughts?
I guess one way to do this would be through a second
createStore
argument that takes something like:Of course, type inference could get a little crazy because
T
would be split between the initial store value and the setters object, this is just a simplified example to illustrate the proposal.Then, you could use it like this:
PD: I realize that while I talk about not wanting to use mutable stores because of its drawbacks, this approach still breaks the model a little bit. However, this is IMO a more controlled way to do it, and it is inspired by the Ariakit react library (in fact, my plan is to try to contribute the solid version of Ariakit and I'd love to keep the API as similar as possible where reasonable).
cc @ryansolid would love your thoughts on this
Beta Was this translation helpful? Give feedback.
All reactions