-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathlocal-state-advanced.reducer.ts
More file actions
74 lines (61 loc) · 2.08 KB
/
local-state-advanced.reducer.ts
File metadata and controls
74 lines (61 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import {Action, combineReducers, createAction, union} from '@ngrx/store';
import {
createFormGroupState,
formGroupReducer,
FormGroupState,
setValue,
updateGroup
} from "../../../../src/ngrx-forms";
export const GetManufacturersAction = createAction('localStateAdvanced/GET_MANUFACTURERS', (countryCode: string) => ({ countryCode: countryCode }));
export const SetManufacturersAction = createAction('localStateAdvanced/SET_MANUFACTURERS', (manufacturers: string[]) => ({ manufacturers: manufacturers }));
export const ManufacturersActions = union({GetManufacturersAction, SetManufacturersAction});
export type ManufacturersActionsTypes = typeof ManufacturersActions;
export interface FormValue {
countryCode: string;
manufacturer: string;
}
export interface LocalState {
manufacturers: string[];
formState: FormGroupState<FormValue>;
}
export const FORM_ID = 'localStateForm';
export const INITIAL_FORM_STATE = createFormGroupState<FormValue>(FORM_ID, {
countryCode: '',
manufacturer: '',
});
export const INITIAL_LOCAL_STATE: LocalState = {
manufacturers: [],
formState: INITIAL_FORM_STATE,
};
const reducers = combineReducers<LocalState>({
manufacturers(manufacturers: string[] = [], a: Action) {
// update from loaded data
if (a.type === SetManufacturersAction.type) {
return a as any['manufacturers'];
}
return manufacturers;
},
formState(fs = INITIAL_FORM_STATE, a: Action) {
return formGroupReducer(fs, a);
},
});
export function reducer(oldState: LocalState = INITIAL_LOCAL_STATE, action: Action) {
// each reducer takes care of its individual state
let state = reducers(oldState, action);
if (state === oldState) {
return state;
}
// one overarching reducer handles inter-dependencies
const formState = updateGroup<FormValue>({
manufacturer: manufacturer => {
if (!state.manufacturers.includes(manufacturer.value)) {
return setValue('')(manufacturer);
}
return manufacturer;
},
})(state.formState);
if (formState !== state.formState) {
state = { ...state, formState };
}
return state;
}