Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put model specific business logic in a Redux app

I am struggling to understand where I should put some of the functionality in the Redux/React app I'm building.

My scenario is as follows, in my current app I have several JS classes that wrap around specific json objects and provide methods to get various parts of the data transformed based on certain criteria. For instance, they have a getProperty('name') method which looks up the current host environment and returns the correct sub property value for that host.

Where would be the correct place to implement this logic in a Redux app? Ideally I'd want to encapsulate it in a model so other developers don't need to reimplement it in every view.

Would transforming the json data into a class in my data loading action and storing that in the store via reducer be right? If so how could I be sure the state doesn't get mutated via a setter method in the class?

Any help/opinions appreciated.

like image 747
monobyte Avatar asked Feb 12 '16 08:02

monobyte


1 Answers

If you want to transform model data for the view, it is appropriate to do it outside the reducers. Usually we recommend you to export functions that take the current state (and potentially other arguments, like an environment in your case) and return whatever the view needs, for example, getVisibleTodos(state). Such functions can be composed similarly to how you compose reducers, and in fact, we recommend defining them alongside the reducers so you don’t forget to change them when your state shape changes.

The shopping cart example demonstrates this approach. However, recalculating all derived state on every state change is inefficient. This is why we recommend to use a library like Reselect that lets you compose selector functions as dependencies of other selector functions, and memoizes the values so they are not recalculated without necessity.

Please refer to Computing Derived Data for more information about this approach.

like image 91
Dan Abramov Avatar answered Sep 22 '22 10:09

Dan Abramov