Keeping your state and store centralized
If you do encounter the need to implement custom selectors, it is highly recommended that you integrate them into your entity facades, rather than consume them directly from components. This does of course assume you are using entity facades, and if you have foregone the use of facades then you may use custom selectors as you normally do with @ngrx.
After creating a custom selector, you will need to determine whether a property or accessor method is appropriate for this new selector in your facade. For non-parameterized selectors, a property is usually most appropriate.
For parameterized selectors, an accessor method may be more appropriate. If however the possible range of input to your parameters is limited then multiple properties that each encompass a particular use case might still be the best option.
Continuing on with our firstCustomer
selector from the previous section, adding this to a CustomerFacade
should be very strait forward:
With a parameterized selector like our prior customerById
example, we should use a method instead of a property to allow passing in the id of the customer to select:
When ready-made just isn't enough
While NgRx Auto-Entity provides quite a bit of ready-made functionality, tracking state for many of the most common elements of entity state including the usual "custom" aspects such as the currently selected entity, loading flags, etc. there may be cases where you still need to create a custom selector. Even when using prefabricated facades, once you get into extending those facades, custom selectors are not uncommon.
Custom selectors are implemented as you have always implemented them. Nothing new or special there. Parameterized selectors may also still be used. Make sure to extract the entityState
property from the return value from buildState
if you need to access the whole state (including all of the additional data tracked by Auto-Entity) for a given entity.
Don't forget to destructure the selectors
map to pull out the specific selectors required for composition into custom selectors. Also remember that nested structures may be destructured inline with modern javascript as well!
Note that it is also possible to create parameterized selectors with @ngrx. You may still implement parameterized selectors with Auto-Entity as well:
Follow the necessary precautions and best practices outlined in the ngrx.io documentation when using parameterized selectors. There are some important caveats to be aware of with their use.
When it comes to using custom selectors, they are used the same as any prefabricated facade property or method. As a quick example, our prior two custom selections added to our CustomerFacade
may be used as so: