Enums are set of named constants. Their ability to create a set of distinct cases makes it best option to use with our ngrx reducers.
We use those enums to represent NGRX actions as
export enum Actions = {
PROGRAM_LOAD = '[PROGRAM] Load Program',
PROGRAM_LOAD_FAIL = '[PROGRAM] Program loading failed',
PROGRAM_LOAD_SUCCESS = '[PROGRAM Program loaded successfully',
PROGRAM_DELETE = '[PROGRAM] Load Program'
}
Can you spot the error in above code snippet there
Take some time and think over it.
Same for me, I also wasn’t able to find it easily (even having the liberty to execute the action). Unwittingly I have spend hours digging to entire NGRX Store until realized the following.
There are two enum properties with same values, what will happen if you request PROGROAM_DELETE. This line supposed to dispatch delete program action but instead will load programs.
This happens because store reducers checks for enum value not enum keys. As we can see in following code snippet
export function reducer(
state = initialState,
action: fromPizzas.PizzasAction
): PizzaState {
switch (action.type) {
case fromPizzas.LOAD_PIZZAS: {
return {
...state,
loading: true,
};
}
}
As you can see on line 5 of above code snippet both fromProgram.LOAD_PROGRAM and fromProgram.PROGRAM_DELETE will fall into same switch case because of having same enum value.
Yes I copied and pasted code that’s why I got this issue. This is because the boilerplate code that NGRX comes (or redux in general).
Conclusion
In conclusion I would say that, boilerplate aside, no doubt we do great sense of freedom once our store is ready. I only found the bug when I started testing my actions. Which also gave the positive reinforcement to continue testing. As testing makes you a better programmer.