Reducers

Now that you've defined how this application's state can be modified, it's time to implement these actions in a reducer.

We'll cover the following...

ngrx reducers

We need to define just how these state changes work. In state.ts, we’ll define the patient reducer, a function that handles the UPDATE_PATIENT and ADD_PATIENTS actions.

This application has only one type of state (an array of patients), but more complex apps have many different values stored in ngrx (user data, form elements, and the like).

Press + to interact
export function patientReducer(state = [], action: PatientAction) { // (1)
switch (action.type) { // (2)
case UPDATE_PATIENT:
return state.map((item, idx) => // (3)
idx === action.payload.index ? action.payload.newPatient : item
);
case ADD_PATIENTS: // (4)
return [...state, ...action.payload];
default: // (5)
return state;
}
}
  • Line 1: Every reducer takes two parameters:the current state and the action to modify that state.
    It’s good practice to include a default value for the state parameter, which becomes the initial
    ...