Skip to content

Still return defaultState in handleActions reducer when no handlers are provided #203

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Apr 16, 2017
Merged
24 changes: 24 additions & 0 deletions src/__tests__/handleActions-test.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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);
}