Reducers

(previousState, action) => newState

Reducer === Pure Function:

=> Just calculations

Functionnal Decomposition

Different pure functions coexist inside reducer:

Reducer Example


        // NgRx example
        export const initialState: State = {
            entities: [],
            pending: false,
            error: null
        }

        export const todoReducer: ActionReducer< State > = (state = initialState, action: todo.TodoActions): State => {
            switch (action.type) {

              case todo.ActionTypes.GET_TODO:
              case todo.ActionTypes.UPDATE_TODO:
              case todo.ActionTypes.REMOVE_TODO:
              case todo.ActionTypes.ADD_TODO: {
                return Object.assign({}, state, { pending: true, error: null })
              }

              case todo.ActionTypes.ADD_TODO_SUCCESS: {
                const newTodo: Todo = < Todo >action.payload;
                return Object.assign({}, state, { entities: [...state.entities, newTodo], pending: false, error: null })
              }

              default: {
                return state
              }
            }
        }
    

Combine Reducer


        import { StoreModule, MetaReducer } from '@ngrx/store';

        # app.module.ts
        StoreModule.forRoot({}, {metaReducers})

        # todo.module.ts => feature module
        StoreModule.forFeature('todo', reducers, {metaReducers}),
    

            function combineReducers(reducers) {
                return function (state = {}, action) {
                    return Object.keys(reducers).reduce((nextState, key) => {
                    // Call every reducer with the part of the state it manages
                    nextState[key] = reducers[key](state[key], action)
                    return nextState
                    }, {})
                }
            }
        

Meta-Reducer || Higher Order Reducer

It's a function that takes a reducer, and returns a new reducer that is able to handle new actions, or to hold more state, delegating control to the inner reducer for the actions it doesn't understand.

Reducer semantic

Different type of reducer designation: