Angular course Β· Module 10: State Management

Classic NgRx Store

2 min read Β·
In this lesson3

NgRx Store is the Redux pattern for Angular - powerful, but more complex.

NgRx Structure

store/
β”œβ”€β”€ samurai.actions.ts    # Actions
β”œβ”€β”€ samurai.reducer.ts    # Reducer
β”œβ”€β”€ samurai.selectors.ts  # Selectors
β”œβ”€β”€ samurai.effects.ts    # Effects (side effects)
└── samurai.state.ts      # State interface

Actions

import { createAction, props } from '@ngrx/store';

// Loading
export const loadSamurai = createAction('[Samurai] Load');
export const loadSamuraiSuccess = createAction(
  '[Samurai] Load Success',
  props<{ samurai: Samurai[] }>()
);
export const loadSamuraiFailure = createAction(
  '[Samurai] Load Failure',
  props<{ error: string }>()
);

// CRUD
export const addSamurai = createAction(
  '[Samurai] Add',
  props<{ samurai: Samurai }>()
);

export const deleteSamurai = createAction(
  '[Samurai] Delete',
  props<{ id: number }>()
);

Reducer

import { createReducer, on } from '@ngrx/store';

export interface SamuraiState {
  samurai: Samurai[];
  loading: boolean;
  error: string | null;
}

const initialState: SamuraiState = {
  samurai: [],
  loading: false,
  error: null
};

export const samuraiReducer = createReducer(
  initialState,

  on(loadSamurai, (state) => ({
    ...state,
    loading: true,
    error: null
  })),

  on(loadSamuraiSuccess, (state, { samurai }) => ({
    ...state,
    samurai,
    loading: false
  })),

  on(loadSamuraiFailure, (state, { error }) => ({
    ...state,
    loading: false,
    error
  })),

  on(addSamurai, (state, { samurai }) => ({
    ...state,
    samurai: [...state.samurai, samurai]
  })),

  on(deleteSamurai, (state, { id }) => ({
    ...state,
    samurai: state.samurai.filter(s => s.id !== id)
  }))
);

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does an Action represent in NgRx?

  2. 2. What does a Reducer do in NgRx when it receives an action?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Complete the actions and reducer for managing samurai in NgRx.

  • Horizontal ordering

    Arrange the createAction call with the action type and props (one line, left to right):

  • Vertical ordering

    Order the actions describing the data loading flow in NgRx (from start to finish):

  • Vertical ordering

    Order the one-way flow in classic NgRx (from event to view):

Useful articles