From 20f73c46d70cccde295ca0a9d6d0ff008983e276 Mon Sep 17 00:00:00 2001 From: Matt Brennan Date: Mon, 5 Nov 2018 13:33:50 +0000 Subject: [PATCH] support default state in x-interaction --- .../__tests__/x-interaction.test.jsx | 14 ++++++++++++++ components/x-interaction/src/Interaction.jsx | 15 ++++++++++++--- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/components/x-interaction/__tests__/x-interaction.test.jsx b/components/x-interaction/__tests__/x-interaction.test.jsx index 3d0d4fcbc..e021090d3 100644 --- a/components/x-interaction/__tests__/x-interaction.test.jsx +++ b/components/x-interaction/__tests__/x-interaction.test.jsx @@ -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(); + + expect( + target.find(Base).prop('foo') + ).toBe(5); + }); + }); describe.skip('server rendering'); diff --git a/components/x-interaction/src/Interaction.jsx b/components/x-interaction/src/Interaction.jsx index 1689210ba..a75163cbf 100644 --- a/components/x-interaction/src/Interaction.jsx +++ b/components/x-interaction/src/Interaction.jsx @@ -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({ @@ -33,11 +41,12 @@ export const withActions = (getActions) => (Component) => { ...initialState }) { const actions = invoke(getActions, initialState); + const defaultState = invoke(getDefaultState, initialState); return