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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With