Closed Jazzmanpw closed 3 years ago
Below is a workaround that may be used to implement the desired behavior. More than that, it even tries to prevent the "default" part from executing if the state was changed by the "switch" reducer, but it's verbose and make much more than it should. It may be much easier to just create a pull request with this fix, but I've never done it before and don't know how one usually does that.
const inc = createAction('INC');
const subtract = createAction('SUBTRACT', res => (v: number) => res(v));
const switchReducer = createReducer(0, handle => [
handle(inc, state => state + 1),
handle(subtract, (state, { payload }) => state - payload),
]);
const reducer: typeof switchReducer = (state, action) => {
const newState = switchReducer(state, action);
if (newState !== state) {
return newState;
}
// this is the "default" part
return state;
};
I propose following API:
const reducer = createReducer(defaultState, handle => [
handle(increment, state => state + 1),
handle(decrement, state => state - 1),
handle.default((state, action) => state)
])
PRs welcome. Fork the next branch and read create-reducer.ts
, create-handler-map.ts
files. Those files need to change.
The changes must be complete. New tests run. There is a couple of other tests that complain about obsolete snapshots, and I'm not sure if I can just ignore them for a moment. I guess, now I'm waiting for review, don't I?
Some checks have failed. I'll try to investigate them on my own.
There are use cases for this. Two examples how I use it:
function derivativeReducer(state, action) { switch (action.type) { case SOME_ACTION: return / some processing /; case ANOTHER_ACTION: return / more processing /; default: return baseReducer(state, action); } }
Do you plan to add something like this? What do you think of this proposal?