Skip to content

Instantly share code, notes, and snippets.

@export-mike
Created March 14, 2017 04:51
Show Gist options
  • Select an option

  • Save export-mike/9f308126f65d0a33fe69398a3e2a667a to your computer and use it in GitHub Desktop.

Select an option

Save export-mike/9f308126f65d0a33fe69398a3e2a667a to your computer and use it in GitHub Desktop.
How Does Redux Work?
import compose from 'recompose/compose';
import EventEmitter from 'event-emitter';
const combineReducers = reducersMap => {
const arrayOfReducers = Object.keys(reducersMap)
.reduce((acc, r) => [...acc, reducersMap[r]], []);
return compose.apply(null, arrayOfReducers);
}
const dispatch = reducers => action => reducers(action);
class Store extends EventEmitter {
constructor(reducer, initialState) {
super(initalState);
this.state = initalState;
this.reducer = reducer;
}
dispatch = action => {
const newState = this.reducer(action);
this.emit('Change', newState, this.getState);
}
getState = () => this.state;
onChange = fn => EventEmitter.prototype.addListener.call(this, 'Change', fn);
}
const reducers = {
form,
loading,
users,
cars
};
const createStore = reducer => initialState => {
return new Store(reducer, initialState);
}
const store = createStore(combineReducers(reducers));
class Provider extends Component {
constructor(props){
this.store = props.store;
this.context.store = this.store;
}
onStoreChange = () => this.setState({});
componentWillMount() {
this.store.addListener(this.onStoreChange);
}
componentWillUnMount(){
this.store.removeListener();
}
render() {
return <this.props.children />
}
}
var connect = function(mapStateToProps, mapDispatchToProps) {
return function (Component) {
return class Connect extends React.Component {
render() {
return (<Component
{...mapStateToProps(this.context.getState(), this.props)}
{...mapDispatchToProps(this.context.dispatch)}
/>);
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment