Skip to content

Commit

Permalink
support default state in x-interaction
Browse files Browse the repository at this point in the history
  • Loading branch information
apaleslimghost committed Nov 5, 2018
1 parent 3f2506b commit 20f73c4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
14 changes: 14 additions & 0 deletions components/x-interaction/__tests__/x-interaction.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,20 @@ describe('x-interaction', () => {
target.find(Base).prop('quux')
).toBe(10);
});

it('should get default state from second argument', async () => {
const Base = () => null;
const Wrapped = withActions({}, {
foo: 5
})(Base);

const target = mount(<Wrapped />);

expect(
target.find(Base).prop('foo')
).toBe(5);
});

});

describe.skip('server rendering');
Expand Down
15 changes: 12 additions & 3 deletions components/x-interaction/src/Interaction.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,27 @@ const invoke = (fnOrObj, ...args) => typeof fnOrObj === 'function'
? fnOrObj(...args)
: fnOrObj;

export const withActions = (getActions) => (Component) => {
const _wraps = { getActions, Component };
export const withActions = (getActions, getDefaultState = {}) => (Component) => {
const _wraps = { getActions, getDefaultState, Component };

// if the component we're wrapping is already wrapped, we don't want
// to wrap it further. so, discard its wrapper and rewrap the original
// component with the new actions on top
if(Component._wraps) {
const wrappedGetActions = Component._wraps.getActions;
const wrappedGetDefaultState = Component._wraps.getDefaultState;

Component = Component._wraps.Component;

getActions = initialState => Object.assign(
invoke(wrappedGetActions, initialState),
invoke(_wraps.getActions, initialState)
);

getDefaultState = initialState => Object.assign(
invoke(wrappedGetDefaultState, initialState),
invoke(_wraps.getDefaultState, initialState)
);
}

function Enhanced({
Expand All @@ -33,11 +41,12 @@ export const withActions = (getActions) => (Component) => {
...initialState
}) {
const actions = invoke(getActions, initialState);
const defaultState = invoke(getDefaultState, initialState);

return <Interaction {...{
id,
Component,
initialState,
initialState: Object.assign({}, defaultState, initialState),
actionsRef,
serialiser,
actions,
Expand Down

0 comments on commit 20f73c4

Please sign in to comment.