Skip to content

Commit

Permalink
feat(store): allow multiple on handlers for the same action in create…
Browse files Browse the repository at this point in the history
…Reducer(#2103)

Closes #1956
  • Loading branch information
zhaosiyang authored and brandonroberts committed Oct 3, 2019
1 parent d560640 commit 9a70262
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
17 changes: 17 additions & 0 deletions modules/store/spec/reducer_creator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,23 @@ import {on} from './modules/store/src/reducer_creator';
state = fooBarReducer(state, bar({ bar: 54 }));
expect(state).toEqual(['[foobar] FOO', '[foobar] BAR']);
});

it('should support "on"s to have identical action types', () => {
const increase = createAction('[COUNTER] increase');

const counterReducer = createReducer(
0,
on(increase, state => state + 1),
on(increase, state => state + 1)
);

expect(typeof counterReducer).toEqual('function');

let state = 5;

state = counterReducer(state, increase());
expect(state).toEqual(7);
});
});
});
});
9 changes: 8 additions & 1 deletion modules/store/src/reducer_creator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,14 @@ export function createReducer<S, A extends Action = Action>(
const map = new Map<string, ActionReducer<S, A>>();
for (let on of ons) {
for (let type of on.types) {
map.set(type, on.reducer);
if (map.has(type)) {
const existingReducer = map.get(type) as ActionReducer<S, A>;
const newReducer: ActionReducer<S, A> = (state, action) =>
on.reducer(existingReducer(state, action), action);
map.set(type, newReducer);
} else {
map.set(type, on.reducer);
}
}
}

Expand Down

0 comments on commit 9a70262

Please sign in to comment.