So, I am using redux, and reselect tool createSelector
to memoize my selectors in mapStateToProps
, and it is great.
Now, I have some normalized data in my store, and a container that needs inter-dependant data from the store.
I am doing this, for the moment, and it works:
const getItemId = props => parseInt(props.match.params.itemId, 10)
const containerSelector = createSelector(getItemId, itemId =>
createSelector(
[getUser, getItem(itemId)],
(user, item) =>
createSelector(
[
getFoo(item.fooId),
getBar(item.barId)
],
(foo, bar) => ({ user, item, foo, bar })
)
)
)
const mapStateToProps = (state, ownProps) =>
containerSelector(ownProps)(state)(state)
export default connect(mapStateToProps)(Container)
Question: is there a better way to do this?
- more readable?
- Better practice?
- More performant? (is this performant?)
Edit:
Thanks to Tho Vu answer, I could made it simpler and memoized, like this:
import { getUser, getItemById, getFooById } from 'selectors'
// Note: getStuffById are selector factories like:
// const getStuffById = id => state => state.stuff.objects[id]
const itemIdSelector = (_, props) => parseInt(props.match.params.itemId, 10)
const itemSelector = (state, props) => {
const itemId = itemIdSelector(state, props)
return getItemById(itemId)(state)
}
const fooSelector = (state, props) => {
const item = itemSelector(state, props)
return item ? getFooById(item.fooId)(state) : null
}
const mapStateToProps = createStructuredSelector({
user: getUser,
itemId: itemIdSelector,
item: itemSelector,
foo: fooSelector
})
But I am still mixed about it? Or maybe it is fine already?