diff --git a/packages/client/src/redux/index.ts b/packages/client/src/redux/index.ts index 1093b5a..b796323 100644 --- a/packages/client/src/redux/index.ts +++ b/packages/client/src/redux/index.ts @@ -1,2 +1,3 @@ export * from './Connector' export * from './TStateSelector' +export * from './pack' diff --git a/packages/client/src/redux/pack.ts b/packages/client/src/redux/pack.ts new file mode 100644 index 0000000..3f3fd46 --- /dev/null +++ b/packages/client/src/redux/pack.ts @@ -0,0 +1,50 @@ +import { ComponentType, PureComponent } from 'react' +import { connect, Omit } from 'react-redux' +import { Dispatch } from 'redux' +import { TStateSelector } from './TStateSelector' + +/** + * This function can be used to pack React components into reusable modules. + * + * For example: + * + * + * function configure( + * actions: Actions, + * getLocalState: (state: State) => LocalState, + * ) { + * pack( + * getLocalState, + * function mapStateToProps(localState: LocalState) { + * return localState, + * }, + * function mapDispatchToProps(dispatch: Dispatch) { + * return bindActionCreators(actions, dispatch) + * }, + * Component + * ) + * } + */ +export function pack< + LocalState, + State, + Props, + StateProps extends Partial, + DispatchProps extends Partial, +>( + getLocalState: TStateSelector, + mapStateToProps: (state: LocalState) => StateProps, + mapDispatchToProps: (dispatch: Dispatch) => DispatchProps, + Component: React.ComponentType, +): ComponentType< + Omit +> { + + return connect( + (state: State) => { + const l = getLocalState(state) + return mapStateToProps(l) + }, + mapDispatchToProps, + )(Component as any) as any +}