Search code examples
angularngrxngrx-store

Reducer name in StoreModule.forRoot()


My question is why does the name of the two highlighted count below need to be the same for the application to work? The doc says forRoot take a reducer as an argument, but why the name of the reducer in forRoot should be the same as the state (count in this case)? I don't see this mentioned anywhere in the doc, thanks!

imports: [BrowserModule, StoreModule.forRoot({ count: counterReducer })],

constructor(private store: Store<{ count: number }>) { this.count$ = store.select('count'); }

(The example is from https://ngrx.io/guide/store)


Solution

  • forRoot (and forFeature) build up the state tree, in this example you end up with the following state tree:

    {
      count: 0
    }
    

    select reads from the state tree, and you have to start at the top level, that's why it needs to be count, because it reads the count property from the state tree.

    An example with a bigger state:

    {
      customers: {
        persons: {
          ...
        }
      }
    }
    

    Would result in the following select to get the persons

    store.select('customers', 'persons')