Search code examples
angulartypescriptngrxstore

how to remove feature from store


I have an app store for my main module (global).

But, I have another module, which is lazy, and contains a featured store. Let's name it users module (with /users route).

  1. When I access the application on homepage (app module), the app store will be loaded.
  2. When I navigate to /users route, users module will be loaded, togheter with users store (featured store)
    • in this moment, my store is computed by /app-store and /users-store.
  3. I navigate outside users and I want to remove /users-store from my state.

I tried in ngOnDestroy of my principal users component to reinitialize the user state (because I don't know how to remove it), but the action is not fired.

ngOnDestroy() {
    this.store.dispatch(fromFeature.resetStoreAction());
}

I need it, because the modules are accesible by roles, and I don't want to keep in memory users-store useless.


Solution

  • You can remove state leafs with removeReducer, it could be that you'll have to re-add the feature manually if the user navigates again to that page tho when you do this. See my blog post An experiment, using the global NgRx Store as a local store for more info.

    Personally, I don't see why this state needs to be removed, if the state is bound to the component's lifecycle - I think a NgRx Component Store would fit your needs better. https://ngrx.io/guide/component-store

     constructor(
        private reducers: ReducerManager,
      ) {
      }
    
    ngOnDestroy() {
      this.reducers.removeReducer('feature-name');
    }