the-dr-lazy / deox

Functional Type-safe Flux Standard Utilities
https://deox.js.org
MIT License
206 stars 12 forks source link

Add "default" section in createReducer() #152

Closed Jazzmanpw closed 3 years ago

Jazzmanpw commented 4 years ago

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); } }


One of the easiest ways is to make the third optional argument that will be used as the default reducer:
```js
createReducer(initState, handle => [
  handle(action, reducer),
], (state, action) => { /* this will be the default reducer */ });

Do you plan to add something like this? What do you think of this proposal?

Jazzmanpw commented 4 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;
};
the-dr-lazy commented 4 years ago

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.

Jazzmanpw commented 4 years ago

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?

Jazzmanpw commented 4 years ago

Some checks have failed. I'll try to investigate them on my own.