Skip to content
This repository was archived by the owner on Aug 23, 2022. It is now read-only.

Commit 7eaed5d

Browse files
committed
Allowing for thunk-like actions in LocalForm.
1 parent 01476ff commit 7eaed5d

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

src/components/local-form-component.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,20 @@ class LocalForm extends React.Component {
1111
this.store = props.store || createStore(combineForms({
1212
[props.model]: props.initialState,
1313
}));
14+
15+
this.dispatch = (action) => {
16+
if (typeof action === 'function') {
17+
return action(this.store.dispatch, this.store.getState);
18+
}
19+
20+
return this.store.dispatch(action);
21+
};
22+
}
23+
24+
componentDidMount() {
25+
if (this.props.getDispatch) {
26+
this.props.getDispatch(this.dispatch);
27+
}
1428
}
1529

1630
render() {
@@ -34,6 +48,7 @@ LocalForm.propTypes = {
3448
// provided props
3549
initialState: PropTypes.any,
3650
model: PropTypes.string.isRequired,
51+
getDispatch: PropTypes.func,
3752
};
3853

3954
LocalForm.defaultProps = {

test/local-forms-spec.js

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/* eslint no-return-assign:0 */
22
import React from 'react';
3-
import { Control, LocalForm } from '../src';
3+
import { Control, LocalForm, actions } from '../src';
44
import TestUtils from 'react-addons-test-utils';
55
import { assert } from 'chai';
66

@@ -96,4 +96,44 @@ describe('local forms', () => {
9696
});
9797
});
9898
});
99+
100+
describe('getDispatch', () => {
101+
let innerModelState;
102+
let dispatcher;
103+
104+
TestUtils.renderIntoDocument(
105+
<LocalForm
106+
onChange={(modelValue) => innerModelState = modelValue}
107+
getDispatch={dispatch => dispatcher = dispatch}
108+
initialState={{
109+
foo: '',
110+
bar: '',
111+
}}
112+
>
113+
<Control.text model=".foo" />
114+
</LocalForm>
115+
);
116+
117+
it('should provide a dispatch function', () => {
118+
assert.isFunction(dispatcher);
119+
});
120+
121+
it('should allow normal dispatch behavior', () => {
122+
dispatcher(actions.change('local.foo', 'changed foo'));
123+
124+
assert.equal(innerModelState.foo, 'changed foo');
125+
});
126+
127+
it('should allow thunk-like behaviour', () => {
128+
dispatcher(actions.merge('local', {
129+
foo: 'FOO',
130+
bar: 'BAR',
131+
}));
132+
133+
assert.deepEqual(innerModelState, {
134+
foo: 'FOO',
135+
bar: 'BAR',
136+
});
137+
});
138+
});
99139
});

0 commit comments

Comments
 (0)