Search⌘ K
AI Features

Reducers

Explore how to define pure ngrx reducers in Angular to handle state changes by processing actions such as updating and adding patients. Understand the importance of returning new state objects, organizing state changes with switch statements, and ensuring proper default cases for reliable application state management.

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).

TypeScript 3.3.4
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
    ...