Skip to content

Commit

Permalink
Use defaultState in handleActions with empty reducer map (#203)
Browse files Browse the repository at this point in the history
close #202
  • Loading branch information
webholics authored and yangmillstheory committed Apr 16, 2017
1 parent bac4527 commit feb9386
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
24 changes: 24 additions & 0 deletions src/__tests__/handleActions-test.js
Expand Up @@ -236,4 +236,28 @@ describe('handleActions', () => {
message: 'hello---me: goodbye'
});
});

it('should return default state with empty handlers and undefined previous state', () => {
const { unhandled } = createActions('UNHANDLED');
const reducer = handleActions({}, defaultState);

expect(reducer(undefined, unhandled())).to.deep.equal(defaultState);
});

it('should return previous defined state with empty handlers', () => {
const { unhandled } = createActions('UNHANDLED');
const reducer = handleActions({}, defaultState);

expect(reducer({ counter: 10 }, unhandled())).to.deep.equal({ counter: 10 });
});

it('should throw an error if handlers object has the wrong type', () => {
const wrongTypeHandlers = [1, 'string', [], null];

wrongTypeHandlers.forEach(wrongTypeHandler => {
expect(
() => handleActions(wrongTypeHandler, defaultState)
).to.throw(Error, 'Expected handlers to be an plain object.');
});
});
});
10 changes: 8 additions & 2 deletions src/handleActions.js
@@ -1,8 +1,14 @@
import isPlainObject from 'lodash/isPlainObject';
import reduceReducers from 'reduce-reducers';
import invariant from 'invariant';
import handleAction from './handleAction';
import ownKeys from './ownKeys';
import reduceReducers from 'reduce-reducers';

export default function handleActions(handlers, defaultState) {
invariant(
isPlainObject(handlers),
'Expected handlers to be an plain object.'
);
const reducers = ownKeys(handlers).map(type =>
handleAction(
type,
Expand All @@ -11,5 +17,5 @@ export default function handleActions(handlers, defaultState) {
)
);
const reducer = reduceReducers(...reducers);
return (state, action) => reducer(state, action);
return (state = defaultState, action) => reducer(state, action);
}

0 comments on commit feb9386

Please sign in to comment.