Skip to content

Instantly share code, notes, and snippets.

@viankakrisna
Last active April 11, 2017 20:27
Show Gist options
  • Save viankakrisna/031b7dc3fab1148fb591f0717cbe47dd to your computer and use it in GitHub Desktop.
Save viankakrisna/031b7dc3fab1148fb591f0717cbe47dd to your computer and use it in GitHub Desktop.
re-implementation of redux and react-redux by 52 LOC https://www.webpackbin.com/bins/-KhSxnW73-R4iCMwdfnW
import React from "react";
let store;
export default function createStore(
reducer,
initialState = {},
...middlewares
) {
const subscribers = [];
let newState = initialState;
store = {
dispatch: action => {
newState = reducer(initialState, action);
subscribers.forEach(f => f(newState, store.dispatch));
},
getState: () => newState,
subscribe: cb => {
subscribers.push(cb);
return () => subscribers.splice(subscribers.indexOf(cb), 1);
}
};
return store;
}
const getStore = () => store;
export const connect = (mapStateToProps = e => null, mapDispatchToProps) =>
Component =>
class ConnectedComponent extends React.Component {
constructor(props) {
super(props);
this.store = getStore();
this.state = mapStateToProps(this.store.getState())
this.unsubscribe = this.store.subscribe(()=>{
this.setState(mapStateToProps(this.store.getState()))
});
}
componentWillUnmount(){
this.unsubscribe()
}
render() {
return (
<Component
{...this.props}
{...this.state}
{...mapDispatchToProps
? mapDispatchToProps(this.store.dispatch)
: { dispatch: this.store.dispatch }}
/>
);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment