Search code examples
angularstatengxs

Should I create a state for a separate page?


I create an application by angular and ngxs for first time. I create store for sharing data. But for some pages that don't share data for example edit a special item, should I create a special store for it, something like item-edit.state.ts?

I tried finding many examples of ngxs but could not anwser this question by myself.


Solution

  • Depending on the size of your application you can have a global state and create separate selectors for your pages. For example, you could have item-edit.selectors.ts like the following:

    
    export class ItemEditingSelectors {
      // uses the global state MyState
      @Selector([MyState])
      static viewModel(state: MyStateModel) {
        // do your selection logic here
      }
    }
    

    I personally like to have selectors doing the heavy lifting logic of parsing my state into what the pages/components need so you can leverage their memoization.

    A plus from this approach is that you decouple your page/components from the shape of your state making it easier to perform changes in your state if needed without big impacts on the consumer page/components.