I've just finished wiring up a redux app, and it's fantastic so far. However, because state is stored in a giant store, you don't have any models that you're accessing your data from.
Let's say I have a model class that stores some information about a user. I'd usually add a function to the class called display_name
that combines the different parts of their name intelligently. With that, my different views could simply call display_name
instead of them needing to know how to calculate it themselves.
Redux explicitly says not to store calculated values in the state, so that leaves it to being defined in the components. This can't possibly be right though, because then you'd end up duplicating this code in every component that needs it.
Where is the proper place to store this logic?
The simplest method is to create utility functions to calculate this data and put them in a separate module that can be used by many components' mapStateToProps
functions. A super-simple example:
import { displayName } from "./utils";
function mapStateToProps(state) {
return {
displayName: displayName(state.user)
};
}
function MyComponent(props) {
return <div>Name: {props.displayName}</div>;
}
export default connect(mapStateToProps)(MyComponent);
Per the Computing Derived Data page in the Redux docs, the suggested approach is using the Reselect library for handling selection and memoization.
If you search Github for Javascript projects that contain the term "createSelector", you should find a number of actual apps that are using Reselect in various ways. Here's three that I turned up: jfurrow/flood, FH-Potsdam/shifted maps, and madou/GW2 Armory
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