Skip to content

Instantly share code, notes, and snippets.

@jide
Last active December 8, 2016 12:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jide/6ae3be65635227ef2552778029d523e9 to your computer and use it in GitHub Desktop.
Save jide/6ae3be65635227ef2552778029d523e9 to your computer and use it in GitHub Desktop.
TodoList.mapStateToProps = state =>
({ todos: getVisibleTodos(state.todos, state.visibilityFilter) })
TodoList.mapDispatchToProps = dispatch =>
({ onTodoClick: id => dispatch(toggleTodo(id)) })
wire(TodoList)
function wire(type) {
const WrappedComponent = type;
class FinalComponent extends WrappedComponent {
componentDidMount() {
if (WrappedComponent.prototype.componentDidMount) {
super.componentDidMount();
}
this[UNSUBSCRIBE] = this.context.store.subscribe(this[HANDLE_CHANGE]);
this[HANDLE_CHANGE]();
}
componentWillUnmount() {
if (WrappedComponent.prototype.componentWillUnmount) {
super.componentWillUnmount();
}
this[UNSUBSCRIBE]();
}
[HANDLE_CHANGE] = () => {
const { mapStateToProps, mapDispatchToProps } = type;
const state = this.context.store.getState();
const stateProps = mapStateToProps ?
mapStateToProps(state, this.props) : undefined;
const dispatchProps = mapDispatchToProps ?
mapDispatchToProps(this.context.store.dispatch, this.props) : undefined;
setProps(this, { ...stateProps, ...dispatchProps });
}
}
// Store a reference to the connected component so we can create an element of it instead of the
// original type in createElement().
Type[COMPONENT] = FinalComponent;
return FinalComponent;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment