Skip to content

Commit 5e78f25

Browse files
simplify handleActions (#109)
1 parent 1dc2449 commit 5e78f25

File tree

4 files changed

+18
-23
lines changed

4 files changed

+18
-23
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,8 @@ handleAction('FETCH_DATA', {
9393
});
9494
```
9595

96+
If either `next()` or `throw()` are `undefined` or `null`, then the identity function is used for that reducer.
97+
9698
The optional third parameter specifies a default or initial state, which is used when `undefined` is passed to the reducer.
9799

98100
### `handleActions(reducerMap, ?defaultState)`

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
"rimraf": "^2.5.3"
4949
},
5050
"dependencies": {
51+
"lodash": "^4.13.1",
5152
"reduce-reducers": "^0.1.0"
5253
}
5354
}

src/createAction.js

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
function identity(t) {
2-
return t;
3-
}
1+
import identity from 'lodash/identity';
42

53
export default function createAction(type, payloadCreator, metaCreator) {
64
const finalPayloadCreator = typeof payloadCreator === 'function'

src/handleAction.js

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,22 @@
1-
function isFunction(val) {
2-
return typeof val === 'function';
3-
}
1+
import isFunction from 'lodash/isFunction';
2+
import identity from 'lodash/identity';
3+
import isNil from 'lodash/isNil';
4+
import isSymbol from 'lodash/isSymbol';
45

56
export default function handleAction(type, reducers, defaultState) {
6-
const typeValue = isFunction(type)
7-
? type.toString()
8-
: type;
9-
10-
return (state = defaultState, action) => {
11-
// If action type does not match, return previous state
12-
if (action.type !== typeValue) return state;
7+
const typeValue = isSymbol(type)
8+
? type
9+
: type.toString();
1310

14-
const handlerKey = action.error === true ? 'throw' : 'next';
11+
const [nextReducer, throwReducer] = isFunction(reducers)
12+
? [reducers, reducers]
13+
: [reducers.next, reducers.throw].map(reducer => (isNil(reducer) ? identity : reducer));
1514

16-
// If function is passed instead of map, use as reducer
17-
if (isFunction(reducers)) {
18-
reducers.next = reducers.throw = reducers;
15+
return (state = defaultState, action) => {
16+
if (action.type !== typeValue) {
17+
return state;
1918
}
2019

21-
// Otherwise, assume an action map was passed
22-
const reducer = reducers[handlerKey];
23-
24-
return isFunction(reducer)
25-
? reducer(state, action)
26-
: state;
20+
return (action.error === true ? throwReducer : nextReducer)(state, action);
2721
};
2822
}

0 commit comments

Comments
 (0)