diff --git a/src/create-multi-action.ts b/src/create-multi-action.ts new file mode 100644 index 0000000..fd06105 --- /dev/null +++ b/src/create-multi-action.ts @@ -0,0 +1,25 @@ +import type { Action, AnyAction } from 'redux'; + +export interface ActionCreator { + (...args: any[]): A; +} + +/** + * Create a multi action. Useful when you have an event in a subdomains that triggers a + * a command action that triggers changes in parent domains. + * + * requires the use of arrayMiddleware + */ +const createMultiAction = ( + event: ActionCreator, + ...commands: ActionCreator[] +) => { + const actionCreator = (...args: any[]): Action[] => [ + event(...args), + ...commands.map((ac) => ac(...args)), + ]; + + return actionCreator; +}; + +export default createMultiAction; diff --git a/src/index.ts b/src/index.ts index 6c244ff..986a547 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,3 +8,4 @@ export { default as handleActions } from './handle-actions'; export { default as arrayMiddleware } from './middlewares/array'; export { default as mapFromAction } from './map-from-action'; export type { MapAction, Updater } from './map-from-action'; +export { default as createMultiAction } from './create-multi-action'; diff --git a/test/create-multi-action.ts b/test/create-multi-action.ts new file mode 100644 index 0000000..39b92a9 --- /dev/null +++ b/test/create-multi-action.ts @@ -0,0 +1,21 @@ +import _ from 'lodash/fp'; + +import { createMultiAction, createAction } from '../src'; + +test('should create a multi action', () => { + const foo = createAction('foo'); + const bar = createAction('bar'); + const ac = createMultiAction(foo, bar); + const actual = ac(); + expect(_.flow(_.head, _.get('type'))(actual)).toBe('foo'); + expect(_.flow(_.tail, _.head, _.get('type'))(actual)).toBe('bar'); +}); + +test('should create a multi action if only event', () => { + // don't know why you would do this. + const foo = createAction('foo'); + const ac = createMultiAction(foo); + const actual = ac(); + expect(_.flow(_.head, _.get('type'))(actual)).toBe('foo'); + expect(_.flow(_.tail, _.head, _.get('type'))(actual)).toBe(undefined); +});