Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ expect(actionThree(3)).to.deep.equal({
});
```

### `handleAction(type, reducer | reducerMap, ?defaultState)`
### `handleAction(type, reducer | reducerMap, defaultState)`

```js
import { handleAction } from 'redux-actions';
Expand All @@ -147,22 +147,22 @@ Otherwise, you can specify separate reducers for `next()` and `throw()`. This AP
handleAction('FETCH_DATA', {
next(state, action) {...},
throw(state, action) {...}
});
}, defaultState);
```

If either `next()` or `throw()` are `undefined` or `null`, then the identity function is used for that reducer.

The optional third parameter specifies a default or initial state, which is used when `undefined` is passed to the reducer.
The third parameter `defaultState` is required, and is used when `undefined` is passed to the reducer.

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

```js
import { handleActions } from 'redux-actions';
```

Creates multiple reducers using `handleAction()` and combines them into a single reducer that handles multiple actions. Accepts a map where the keys are passed as the first parameter to `handleAction()` (the action type), and the values are passed as the second parameter (either a reducer or reducer map).

The optional second parameter specifies a default or initial state, which is used when `undefined` is passed to the reducer.
The second parameter `defaultState` is required, and is used when `undefined` is passed to the reducer.

(Internally, `handleActions()` works by applying multiple reducers in sequence using [reduce-reducers](https://github.com/acdlite/reduce-reducers).)

Expand Down
50 changes: 33 additions & 17 deletions src/__tests__/handleAction-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,18 @@ import { handleAction, createAction, createActions, combineActions } from '../';
describe('handleAction()', () => {
const type = 'TYPE';
const prevState = { counter: 3 };
const defaultState = { counter: 0 };

describe('single handler form', () => {
it('should throw an error if defaultState is not specified', () => {
expect(() => {
handleAction(type, undefined);
}).to.throw(Error, 'Expected defaultState for reducer handling TYPE to be defined');
});

describe('resulting reducer', () => {
it('returns previous state if type does not match', () => {
const reducer = handleAction('NOTTYPE', () => null);
const reducer = handleAction('NOTTYPE', () => null, defaultState);
expect(reducer(prevState, { type })).to.equal(prevState);
});

Expand All @@ -23,7 +30,7 @@ describe('handleAction()', () => {
it('accepts single function as handler', () => {
const reducer = handleAction(type, (state, action) => ({
counter: state.counter + action.payload
}));
}), defaultState);
expect(reducer(prevState, { type, payload: 7 }))
.to.deep.equal({
counter: 10
Expand All @@ -34,15 +41,15 @@ describe('handleAction()', () => {
const incrementAction = createAction(type);
const reducer = handleAction(incrementAction, (state, action) => ({
counter: state.counter + action.payload
}));
}), defaultState);

expect(reducer(prevState, incrementAction(7)))
.to.deep.equal({
counter: 10
});
});

it('accepts single function as handler and a default state', () => {
it('accepts a default state used when the previous state is undefined', () => {
const reducer = handleAction(type, (state, action) => ({
counter: state.counter + action.payload
}), { counter: 3 });
Expand All @@ -58,20 +65,26 @@ describe('handleAction()', () => {

const reducer = handleAction(increment, (state, { payload }) => ({
counter: state.counter + payload
}), { counter: 3 });
}), defaultState);

expect(reducer(undefined, increment(7)))
.to.deep.equal({
counter: 10
counter: 7
});
});
});
});

describe('map of handlers form', () => {
it('should throw an error if defaultState is not specified', () => {
expect(() => {
handleAction(type, { next: () => null });
}).to.throw(Error, 'Expected defaultState for reducer handling TYPE to be defined');
});

describe('resulting reducer', () => {
it('returns previous state if type does not match', () => {
const reducer = handleAction('NOTTYPE', { next: () => null });
const reducer = handleAction('NOTTYPE', { next: () => null }, defaultState);
expect(reducer(prevState, { type })).to.equal(prevState);
});

Expand All @@ -80,7 +93,7 @@ describe('handleAction()', () => {
next: (state, action) => ({
counter: state.counter + action.payload
})
});
}, defaultState);
expect(reducer(prevState, { type, payload: 7 }))
.to.deep.equal({
counter: 10
Expand All @@ -92,7 +105,7 @@ describe('handleAction()', () => {
throw: (state, action) => ({
counter: state.counter + action.payload
})
});
}, defaultState);

expect(reducer(prevState, { type, payload: 7, error: true }))
.to.deep.equal({
Expand All @@ -101,7 +114,7 @@ describe('handleAction()', () => {
});

it('returns previous state if matching handler is not function', () => {
const reducer = handleAction(type, { next: null, error: 123 });
const reducer = handleAction(type, { next: null, error: 123 }, defaultState);
expect(reducer(prevState, { type, payload: 123 })).to.equal(prevState);
expect(reducer(prevState, { type, payload: 123, error: true }))
.to.equal(prevState);
Expand All @@ -114,7 +127,8 @@ describe('handleAction()', () => {
const action1 = createAction('ACTION_1');
const reducer = handleAction(
combineActions(action1, 'ACTION_2', 'ACTION_3'),
(state, { payload }) => ({ ...state, number: state.number + payload })
(state, { payload }) => ({ ...state, number: state.number + payload }),
defaultState
);

expect(reducer({ number: 1 }, action1(1))).to.deep.equal({ number: 2 });
Expand All @@ -128,7 +142,7 @@ describe('handleAction()', () => {
next(state, { payload }) {
return { ...state, number: state.number + payload };
}
});
}, defaultState);

expect(reducer({ number: 1 }, action1(1))).to.deep.equal({ number: 2 });
expect(reducer({ number: 1 }, { type: 'ACTION_2', payload: 2 })).to.deep.equal({ number: 3 });
Expand All @@ -145,7 +159,7 @@ describe('handleAction()', () => {
throw(state) {
return { ...state, threw: true };
}
});
}, defaultState);
const error = new Error;

expect(reducer({ number: 0 }, action1(error)))
Expand All @@ -160,6 +174,7 @@ describe('handleAction()', () => {
const reducer = handleAction(
combineActions('ACTION_1', 'ACTION_2'),
(state, { payload }) => ({ ...state, state: state.number + payload }),
defaultState
);

const state = { number: 0 };
Expand All @@ -171,11 +186,11 @@ describe('handleAction()', () => {
const reducer = handleAction(
combineActions('INCREMENT', 'DECREMENT'),
(state, { payload }) => ({ ...state, counter: state.counter + payload }),
{ counter: 10 }
defaultState
);

expect(reducer(undefined, { type: 'INCREMENT', payload: +1 })).to.deep.equal({ counter: 11 });
expect(reducer(undefined, { type: 'DECREMENT', payload: -1 })).to.deep.equal({ counter: 9 });
expect(reducer(undefined, { type: 'INCREMENT', payload: +1 })).to.deep.equal({ counter: +1 });
expect(reducer(undefined, { type: 'DECREMENT', payload: -1 })).to.deep.equal({ counter: -1 });
});

it('should handle combined actions with symbols', () => {
Expand All @@ -184,7 +199,8 @@ describe('handleAction()', () => {
const action3 = createAction(Symbol('ACTION_3'));
const reducer = handleAction(
combineActions(action1, action2, action3),
(state, { payload }) => ({ ...state, number: state.number + payload })
(state, { payload }) => ({ ...state, number: state.number + payload }),
defaultState
);

expect(reducer({ number: 0 }, action1(1)))
Expand Down
37 changes: 28 additions & 9 deletions src/__tests__/handleActions-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,25 @@ import { expect } from 'chai';
import { handleActions, createAction, createActions, combineActions } from '../';

describe('handleActions', () => {
const defaultState = { counter: 0 };

it('should throw an error when defaultState is not specified', () => {
expect(() => {
handleActions({
INCREMENT: ({ counter }, { payload: amount }) => ({
counter: counter + amount
}),

DECREMENT: ({ counter }, { payload: amount }) => ({
counter: counter - amount
})
});
}).to.throw(
Error,
'Expected defaultState for reducer handling INCREMENT, DECREMENT to be defined'
);
});

it('create a single handler from a map of multiple action handlers', () => {
const reducer = handleActions({
INCREMENT: ({ counter }, { payload: amount }) => ({
Expand All @@ -11,7 +30,7 @@ describe('handleActions', () => {
DECREMENT: ({ counter }, { payload: amount }) => ({
counter: counter - amount
})
});
}, defaultState);

expect(reducer({ counter: 3 }, { type: 'INCREMENT', payload: 7 }))
.to.deep.equal({
Expand All @@ -30,15 +49,15 @@ describe('handleActions', () => {
[INCREMENT]: ({ counter }, { payload: amount }) => ({
counter: counter + amount
})
});
}, defaultState);

expect(reducer({ counter: 3 }, { type: INCREMENT, payload: 7 }))
.to.deep.equal({
counter: 10
});
});

it('accepts a default state as the second parameter', () => {
it('accepts a default state used when previous state is undefined', () => {
const reducer = handleActions({
INCREMENT: ({ counter }, { payload: amount }) => ({
counter: counter + amount
Expand All @@ -61,7 +80,7 @@ describe('handleActions', () => {
[incrementAction]: ({ counter }, { payload: amount }) => ({
counter: counter + amount
})
});
}, defaultState);

expect(reducer({ counter: 3 }, incrementAction(7)))
.to.deep.equal({
Expand All @@ -81,12 +100,12 @@ describe('handleActions', () => {
[combineActions(increment, decrement)](state, { payload: { amount } }) {
return { ...state, counter: state.counter + amount };
}
}, initialState);
}, defaultState);

expect(reducer(initialState, increment(5))).to.deep.equal({ counter: 15 });
expect(reducer(initialState, decrement(5))).to.deep.equal({ counter: 5 });
expect(reducer(initialState, { type: 'NOT_TYPE', payload: 1000 })).to.equal(initialState);
expect(reducer(undefined, increment(5))).to.deep.equal({ counter: 15 });
expect(reducer(undefined, increment(5))).to.deep.equal({ counter: 5 });
});

it('should accept combined actions as action types in the next/throw form', () => {
Expand All @@ -107,14 +126,14 @@ describe('handleActions', () => {
return { ...state, counter: 0 };
}
}
}, initialState);
}, defaultState);
const error = new Error;

// non-errors
expect(reducer(initialState, increment(5))).to.deep.equal({ counter: 15 });
expect(reducer(initialState, decrement(5))).to.deep.equal({ counter: 5 });
expect(reducer(initialState, { type: 'NOT_TYPE', payload: 1000 })).to.equal(initialState);
expect(reducer(undefined, increment(5))).to.deep.equal({ counter: 15 });
expect(reducer(undefined, increment(5))).to.deep.equal({ counter: 5 });

// errors
expect(
Expand All @@ -136,7 +155,7 @@ describe('handleActions', () => {
[decrement]: ({ counter }, { payload }) => ({
counter: counter - payload
})
});
}, defaultState);

expect(reducer({ counter: 3 }, increment(2)))
.to.deep.equal({
Expand Down
9 changes: 9 additions & 0 deletions src/assertDefaultState.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import isUndefined from 'lodash/isUndefined';

export default function assertDefaultState(defaultState, actionTypes) {
if (isUndefined(defaultState)) {
throw new Error(
`Expected defaultState for reducer handling ${actionTypes.join(', ')} to be defined`
);
}
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd suggest to move this function to a folder named utils and name that file assertions.js or sth like this, where we can write more functions like this in a single file.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generally that's a good idea to extract the assertions 👍

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, we will rewrite this later with invariant, correct?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, or we may as well do it now.

2 changes: 2 additions & 0 deletions src/handleAction.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import isFunction from 'lodash/isFunction';
import identity from 'lodash/identity';
import isNil from 'lodash/isNil';
import assertDefaultState from './assertDefaultState';
import includes from 'lodash/includes';
import { ACTION_TYPE_DELIMITER } from './combineActions';

export default function handleAction(actionType, reducers, defaultState) {
const actionTypes = actionType.toString().split(ACTION_TYPE_DELIMITER);
assertDefaultState(defaultState, actionTypes);

const [nextReducer, throwReducer] = isFunction(reducers)
? [reducers, reducers]
Expand Down
8 changes: 6 additions & 2 deletions src/handleActions.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import handleAction from './handleAction';
import ownKeys from './ownKeys';
import assertDefaultState from './assertDefaultState';
import reduceReducers from 'reduce-reducers';

export default function handleActions(handlers, defaultState) {
const reducers = ownKeys(handlers).map(type => handleAction(type, handlers[type]));
const actionTypes = ownKeys(handlers);
assertDefaultState(defaultState, actionTypes);

const reducers = actionTypes.map(type => handleAction(type, handlers[type], defaultState));
const reducer = reduceReducers(...reducers);

return (state = defaultState, action) => reducer(state, action);
return (state, action) => reducer(state, action);
}