1
votes

I was reviewing the code for the example application provided by NgRx. I noticed that each reducer function in the example application has a return value that is typed by the State interface for that particular reducer. For example, the books reducer has the following code:

export interface State {
  ids: string[];
  entities: { [id: string]: Book };
  selectedBookId: string | null;
}

export const initialState: State = {
  ids: [],
  entities: {},
  selectedBookId: null,
};

export function reducer(
  state = initialState,
  action: book.Actions | collection.Actions
): State {

Later on, I was reading a book about NgRx titled Reactive Programming with Angular and NgRx by Oren Farhi, and came across a code snippet showing the common body structure of a reducer function (on pages 24-25.) The code for the common structure shows the return value of the reducer function as being typed by ActionReducer with State as the type parameter (called SomeInterface rather than State in this case):

export interface SomeInterface {
  items: Item[],
  filter: string
}

let initialState: SomeInterface = {
  items: [],
  filter: ''
}

export function MyReducer (
  state: SomeInterface = initialState,
  action: Action
): ActionReducer<SomeInterface> {

Why does one code sample use State and the other uses ActionReducer with State as the type parameter for the return value of reducer functions? Why would one choose one of these function signatures over the other? What purpose does each serve?

The book is written for NgRx 2.2.1 whereas the example application is for the latest version of NgRx (version 4.1.1.) I’m guessing that the difference in return types cannot simply be explained by the difference in NgRx versions, as the latest version of NgRx has ActionReducer as well.

Thank you!

1
Use this medium blog to set up for ngrx-4.0Aravind

1 Answers

6
votes

ActionReducer is a collection of reducers which is passed to the StoreModule during imports

  • Reducer should always return the type of the initial state(SomeInterface in your case)

    export interface SomeInterface{
       ....
    }
    const initialState: SomeInterface= {
       ....
    };
    export function reducer(state = initialState, action: Actions): SomeInterface{...}
    
  • ActionReducer should be a collection of reducers which expects a type interface which will be the app store interface of the application and this is collection is called as Reducer Factory

    export const reducers: ActionReducerMap<AppStore> = {
           someInterfacerSlice: someInterface.reducer,
    };
    
  • Define a global app store interface for the module as below,

    export interface AppStore {
          someInterfaceSlice: SomeInterface;
          stateSlice: StateSlice;
    }