We use cookies to enhance your experience on the site
CodeWorlds

Classic NgRx Store

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

NgRx Structure

1store/
2├── samurai.actions.ts    # Actions
3├── samurai.reducer.ts    # Reducer
4├── samurai.selectors.ts  # Selectors
5├── samurai.effects.ts    # Effects (side effects)
6└── samurai.state.ts      # State interface

Actions

1import { createAction, props } from '@ngrx/store';
2
3// Loading
4export const loadSamurai = createAction('[Samurai] Load');
5export const loadSamuraiSuccess = createAction(
6  '[Samurai] Load Success',
7  props<{ samurai: Samurai[] }>()
8);
9export const loadSamuraiFailure = createAction(
10  '[Samurai] Load Failure',
11  props<{ error: string }>()
12);
13
14// CRUD
15export const addSamurai = createAction(
16  '[Samurai] Add',
17  props<{ samurai: Samurai }>()
18);
19
20export const deleteSamurai = createAction(
21  '[Samurai] Delete',
22  props<{ id: number }>()
23);

Reducer

1import { createReducer, on } from '@ngrx/store';
2
3export interface SamuraiState {
4  samurai: Samurai[];
5  loading: boolean;
6  error: string | null;
7}
8
9const initialState: SamuraiState = {
10  samurai: [],
11  loading: false,
12  error: null
13};
14
15export const samuraiReducer = createReducer(
16  initialState,
17
18  on(loadSamurai, (state) => ({
19    ...state,
20    loading: true,
21    error: null
22  })),
23
24  on(loadSamuraiSuccess, (state, { samurai }) => ({
25    ...state,
26    samurai,
27    loading: false
28  })),
29
30  on(loadSamuraiFailure, (state, { error }) => ({
31    ...state,
32    loading: false,
33    error
34  })),
35
36  on(addSamurai, (state, { samurai }) => ({
37    ...state,
38    samurai: [...state.samurai, samurai]
39  })),
40
41  on(deleteSamurai, (state, { id }) => ({
42    ...state,
43    samurai: state.samurai.filter(s => s.id !== id)
44  }))
45);
Go to CodeWorlds