DEV Community

Discussion on: Where to initiate data load in NgRx

Collapse
 
jonrimmer profile image
Jon Rimmer

This is a good question, and it's one I've struggled with myself, and I'm not sure there is a perfect (or even a good) answer for NgRx / Redux as it stands. Usually what I end up doing is having the component(s) interested in a particular entity dispatch a "load" action on ngInit, and then have an effect on this action that checks whether the entity is already present in the store, and then loads it from the back-end if its not. You can mirror this with an "unload" action when the component is destroyed which clears the entity out of the store, so reducing the amount of data you're storing.

However, I have often thought there is room in NgRx for something like a reference-counted selector, where the first subscription to a selector dispatches a "load" event, which can load a resource into the store, and where the subscriber count going back down to zero dispatches an "unload" event. RxJS already has capabilities for performing reference counting on shared observables, so you might be able to use this to create smart selectors in this fashion. I hope to experiment with doing this myself some time, but I haven't yet got around it to it.