Skip to content

Commit

Permalink
✨ Introduce mapStateToProps factory functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
NeoLegends committed Dec 28, 2017
1 parent 01151ed commit 82cb97b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "fit-html",
"version": "0.3.7",
"version": "0.3.8",
"description": "5KB functional Web Components without bloat",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
19 changes: 17 additions & 2 deletions src/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ export interface MapDispatchToPropsFn<S, P, OP> {
(dispatch: Dispatch<S>, ownProps: OP): P;
}

export interface MapStateToPropsFactory<S, P, OP> {
(): MapStateToPropsFn<S, P, OP>
}

/**
* A 💪 web component.
*
Expand Down Expand Up @@ -85,12 +89,13 @@ export { html };
* @template S, SP, DP, OP
*/
export default function connect<S, SP, DP, OP = {}>(
mapStateToProps: MapStateToPropsFn<S, SP, OP>,
mapStateToProps: MapStateToPropsFactory<S, SP, OP> | MapStateToPropsFn<S, SP, OP>,
mapDispatchToProps: MapDispatchToPropsFn<S, DP, OP> | DP,
templateFn: (props: SP & DP) => TemplateResult
): FitElement<S, SP & DP, OP> {
return class extends HTMLElement {
_preparedDispatch: MapDispatchToPropsFn<S, DP, OP> | ActionCreatorsMapObject;
_preparedMapStateToProps: MapStateToPropsFn<S, SP, OP>;
_previousProps: SP & DP | null = null;
_renderEnqueued: boolean = false;
_store: Store<S>;
Expand All @@ -103,6 +108,10 @@ export default function connect<S, SP, DP, OP = {}>(
connectedCallback() {
this.attachShadow({ mode: 'open' });

this._preparedMapStateToProps = isFactory(mapStateToProps)
? mapStateToProps()
: mapStateToProps;

const store = this.getStore();
this._preparedDispatch = isFunction(mapDispatchToProps)
? mapDispatchToProps
Expand Down Expand Up @@ -160,7 +169,7 @@ export default function connect<S, SP, DP, OP = {}>(
const store = this.getStore();
return Object.assign(
{},
mapStateToProps(store.getState(), ownProps),
this._preparedMapStateToProps(store.getState(), ownProps),
isFunction(this._preparedDispatch)
? this._preparedDispatch(store.dispatch, ownProps)
: this._preparedDispatch
Expand Down Expand Up @@ -203,3 +212,9 @@ export default function connect<S, SP, DP, OP = {}>(
}
} as any;
}

function isFactory<S, P, OP>(
fn: MapStateToPropsFactory<S, P, OP> | MapStateToPropsFn<S, P, OP>
): fn is MapStateToPropsFactory<S, P, OP> {
return fn.length === 0;
}

0 comments on commit 82cb97b

Please sign in to comment.