Search code examples
angularreduxngrx

How to use more than one NGRX action that does the same thing following "action hygiene" guideline?


If I have two or more NGRX actions that do the same thing, but are triggered at different parts of my application, can I use one action to perform this while at the same time differentiating the action string in my NGRX log? I ask because when writing actions and trying to follow the "action hygiene" principles where actions should be specific to an event and can be readable a year later and tell the developer exactly where in the app the action was fired, I want to limit as much NGRX boilerplate as possible.

For example: I have a "AddTodo" action. This action can be performed in two spots in my application - one on a "Todo List" page, and the other on a "Todo Details" page. Each action is unique to the page they are triggered from, but they do the exact same thing; they add a new Todo item to my state object.

const TODO_LIST = '[Todo List]';
const TODO_DETAILS = '[Todo Details]';

export const TODO_LIST_ADD = `${TODO_LIST} Add`;
export const TODO_DETAILS_ADD = `${TODO_DETAILS} Add`;

export class TodoListAdd implements Action {
    readonly type = TODO_LIST_ADD;
    constructor(public payload: Todo) { }
}

export class TodoDetailsAdd implements Action {
    readonly type = TODO_DETAILS_ADD;
    constructor(public payload: Todo) { }
}

export function todoReducer(state = initialState, action: Action): TodoState {
    switch (action.type) {
        case actions.TODO_LIST_ADD:
        case actions.TODO_DETAILS_ADD:
            return {
                ...state,
                todo: (action as actions.TodoListAdd | actions.TodoDetailsAdd).payload,
            }
        default:
            return state;
    }
}

If wanting to keep action hygiene, is this the only way to do it? There are two actions that do the exact same thing, the only difference is the string type that distinguishes them in the NGRX event log. I would love it there was a way to reduce the amount of boilerplate by coupling the action creators without losing the specificity of the type.

Thanks,


Solution

  • Yes, if you follow good action hygiene this is the only way.

    However, you could provide a context to your action as described here https://medium.com/javascript-everyday/reusable-action-creators-with-context-2a31dca98192.