question to ngrx users a…

2 minute read

question to ngrx users about best practices: when I define a action reducer map as a forFeature store and this map contains 3-4 reducers. is it really best practice to define the selectors first isolated within their reducers and then again outside of the reducers by selecting the feature, then selecting the sub state of the action reducer map and finally selecting the actual porperty by using that substate and the imported isolated selector of that reducer (possibly all in an store/index.ts file)?

Responses:

basically this makes me repeat all selectors from all substates in this index file?

I understand the benefit of that: isolation of substates - but it seems sooo repetitive

No… That sounds wrong. We have one file with selectors, one file with reducers, one file with actions. Each gets used once (where it needs to) although selectors never use actions and reducers never used selectors and actions use neither.

Unless I misunderstood your question

We also expose the state via a facade.

Index only exports the facade (and associated module with forfeiture)

this is my state…

feature is a forFeatture state and is a map of multiple sub reducers, where sub1 is one of them

I want to select prop1 from sub1

sub1 is not aware of other sub states, nor of its parent state

maybe ngrx guru knows something? :slightly_smiling_face:

basically, in the subreducer I have something like export const getIsLoading = (state: State) => state.isLoading and in my reducer map I then have export const isLoading = createSelector(selectSub1State, fromSub1State.getIsLoading)

Yes, that’s what I recommend personally. The selectors defined in the reducer file are getters, which mainly just pick properties off the state. You may use createSelector to combine some local stuff there. The higher-level selectors that always use createSelector are more complex, could combine multiple selectors, and tie your “global state” to your local selector. It also makes the reducer selectors more portable

You can inline them if that’s not a priority.

Thanks but this means basically for every prop in the reducer I have a getter in the reducer file and the selector for it in the reducer map (or a special selector file). As I said I am totally aware of the benefits, but it really feels overengineered sometimes

But as we do have a large application with mutliple teams, I suppose the benefits outweigh the drawbacks

Yea, that’s why I said me personally. Having a selectors file with inlined functions is fine also. File layout differences aside, this is what we use this as an example in our workshop https://github.com/CodeSequence/ngrx-workshop-ngconf2020/blob/complete/src/app/shared/state/index.ts

Updated: