valtio-factory - create "stores" using the factory pattern #348
Replies: 2 comments
-
Epic package! 1) I have variables depending on other variables, that migth depend on other variables...For example, lets say we have: Right now i'm checking this package: https://github.com/datavis-tech/topologica 2) My store definition is dynamicI store those formulas on the DB, kind of google sheet / excel. This means i CAN'T create the store directly in my code, I need to read the DB, interpret it and create the store and its formulas after reading the DB. This is where valtio-factory might help? What do you think? |
Beta Was this translation helpful? Give feedback.
-
Cool! Love this. Even cooler if it uses the |
Beta Was this translation helpful? Give feedback.
-
I'd like to share a package I created, valtio-factory (CodeSandbox). It provides a somewhat opinionated solution on top of valtio to create "stores" (state, derived state, actions, subscriptions) using the factory pattern:
In general, it simplifies and reduces the boilerplate for doing the following things:
I had the idea to create valtio-factory when I was working on a react-native app that was previously using MobX-State-Tree. In that project I needed to achieve several objectives:
Declare the app's state model and its actions
Using the factory pattern, declaring state, derived state, and actions all together in a concise way is straightforward.
At the same time, the state does not need to be initialised until later, when the
create
method is called."Inject" dependencies into state-dependent logic
A pitfall of simple state management libraries has often been that external dependencies of the business logic (e.g. API clients) must be initialised inside the business logic itself or be imported as "singleton" instances.
With the
context
object, valtio-factory stores can declare an abstract interface that will be satisfied with a concrete implementation on initialisation. This can also be useful for testing, as the external dependencies can be easily mocked.Initialise stores with persisted state
Because stores can be declared and created later, it's easy to come up with a pattern of serialising state to, e.g., async storage and initialising them when the app is started (i.e. when the React component tree is first rendered).
Compose stores
valtio-factory can also compose stores (factories) into objects. That way it's possible to declare a single "root store" that will be passed to the application.
valtio-factory is designed as a complement to valtio. The result of the
create
method is a proxy object that can be used with all existing valtio utilities. While vanilla valtio is simpler and more flexible, I believe valtio-factory can be a great option for more complex applications that might otherwise use solutions like Redux+Saga or MobX-State-Tree.Keen to read your thoughts and feedback!
Beta Was this translation helpful? Give feedback.
All reactions