nuclear-js icon indicating copy to clipboard operation
nuclear-js copied to clipboard

[Question] Data store dependency

Open mtermoul opened this issue 9 years ago • 3 comments

I have StoreA and StoreB that need data from StoreA, do some calculation and store the stats. Anytime StoreA changes, StoreB do the calculations and store the latest stats.

Do you know how to implement this in NuclearJS?

I was thinking to use getters, since they have the ability to declare data dependency, but getters don't have a state that can store data.

mtermoul avatar Jan 28 '16 15:01 mtermoul

If you can determine the stats for the StoreB just by looking at the payload of action that updates StoreA then you can just subscribe to that action with StoreB. Otherwise, you will probably need to dispatch 2 actions. 1st to update the StoreA and the 2nd that will pass the wanted StoreA data to StoreB. But, also, if you can always get the stats by looking at the StoreA state why not create a specific getter that returns the stats and use it wherever you need? If you bind it to the component state the nuclearjs way it'l always update the component with the latest data.

apisurfer avatar Jan 28 '16 20:01 apisurfer

I think dispatching two actions would work best for me. because the updates to StoreA are incremental, therefore I only need to run the calculation on the diff data. So now I have:

module X ---> dispatch 20 records ----> StoreA -----> dispatch 20 records -----> StoreB -----> calculate stats for 20 records ----> store stats on StoreB

new updates -----> dispatch 5 records ----> StoreA ----> dispatch 5 records ----> StoreB -----> calculate stats for 5 records -----> add new stats to old stats ---> store sum(stats) in StoreB

so I guess that this is working, but not sure if this is the best solution.

mtermoul avatar Jan 28 '16 21:01 mtermoul

Based on the current description of your data model, to me it sounds like the a getter would be most appropriate.

I think that Stores should only store the minimum state necessary for the application, and anything that can be derived should be a getter. If whatever is calculated in StoreB is purely derived from the latest state of StoreA, then I would argue that it should be a getter and not a piece of state.

As long as all data retrievals are abstracted through getters, then the part of the application that is retrieving this data should not care whether StatB was maintained in a store or if it was just derived in a getter.

If the above does not work for you, another thing to consider is: Do you need StoreB to be a separate store? Maybe you could move this functionality into StoreA as another property. This way, when StoreA receives its action, it can first do its original processing, then do the secondary calculation (originally from StoreB) as part of the same action handler.

lawrence-yu avatar Feb 11 '16 22:02 lawrence-yu