Reputation: 417
What is to correct way to declare an "INIT_ACTION" that all reducers in the ActionReducerMap can react upon?
this an example of how my code, I need all 3 reducers (images, tags, addedTags) to react to a single action :
import { ActionReducerMap, createFeatureSelector } from '@ngrx/store';
import * as fromRoot from '../../../store';
import * as fromImages from './image.reducer';
import * as fromTags from './tag.reducer';
import * as fromAddedTags from './added-tag.reducer';
export interface AnalysisState {
images: fromImages.State;
tags: fromTags.State;
addedTags: fromTags.State;
}
export interface State extends fromRoot.State {
analysis: AnalysisState;
}
export const reducers: ActionReducerMap<AnalysisState> = {
images: fromImages.reducer,
tags: fromTags.reducer,
addedTags: fromAddedTags.reducer
};
export const getAnlysisState = createFeatureSelector<AnalysisState>('analysis');
this is an example actions file:
import { Action } from '@ngrx/store';
import { Tag } from '../../models/tag.model';
export const enum AddedTagActionTypes {
ADD_TAG = '[ANALYSIS] - Add Tag'
}
export class AddTag implements Action {
readonly type = AddedTagActionTypes.ADD_TAG;
constructor(public payload: Tag) {}
}
export type AddedTagActions = AddTag;
and this is an example reducer:
import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';
import * as fromAddedTag from '../actions/added-tag.actions';
import { Tag } from '../../models/tag.model';
export interface State extends EntityState<Tag> {}
export const adapter: EntityAdapter<Tag> = createEntityAdapter<Tag>({
selectId: tag => tag.id
});
export const initialState: State = adapter.getInitialState({});
export function reducer(state = initialState, action: fromAddedTag.AddedTagActions): State {
switch (action.type) {
case fromAddedTag.AddedTagActionTypes.ADD_TAG: {
return adapter.addOne(action.payload, state);
}
default: {
return state;
}
}
}
const { selectIds, selectEntities, selectAll, selectTotal } = adapter.getSelectors();
export const getAllAddedTags = selectAll;
Upvotes: 5
Views: 915
Reputation: 57046
An action passes through all reducers. Therefore, if you simply put a case statement for that action in all 3 reducers then it will hit all 3 case statements.
If there is no case statement for a specific action in a reducer then the default case statement will be triggered which simply returns the original state, leaving it unmodified.
This assumes that you are not lazy loading reducers. A reducer will of course only be triggered if it is loaded.
Upvotes: 4