Last active
June 29, 2018 10:14
-
-
Save antsmartian/4f46a70343ba6b9ef4109a7ab944189e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component, createContext } from 'react' | |
function initStore(store) { | |
const Context = createContext(); | |
class Provider extends React.Component { | |
constructor() { | |
super(); | |
this.state = store.initialState; | |
} | |
selector = (value) => { | |
return Object.keys(store.actions).reduce( | |
(fn, key) => ({ | |
...fn, | |
[key]: (...args) => { | |
let result = store.actions[key](this.state[value], ...args); | |
this.setState(result); | |
}, | |
}), | |
{}, | |
); | |
}; | |
render() { | |
return ( | |
<Context.Provider | |
value={{ | |
state: this.state, | |
selector : this.selector | |
}}> | |
{this.props.children} | |
</Context.Provider> | |
) | |
} | |
} | |
const connect = select => Component => props => { | |
return ( | |
<Context.Consumer select={select}> | |
{({ state, selector}) => ( | |
<Component state={state} actions={selector(select)} /> | |
)} | |
</Context.Consumer> | |
) | |
}; | |
return { | |
Provider, | |
connect | |
} | |
} | |
const store = { | |
initialState: { | |
count: 1 | |
}, | |
actions: { | |
increment: (value) => ({ count: value + 1 }), | |
decrement: (value) => ({ count: value - 1 }) | |
} | |
}; | |
const { Provider, connect } = initStore(store); | |
//Example 1 | |
let SimpleCount = ({ state, actions }) => ( | |
<div> | |
{state.count} | |
<button onClick={actions.increment}>+</button> | |
<button onClick={actions.decrement}>-</button> | |
</div> | |
); | |
Count = connect('count')(Count); | |
export default class ContextState extends Component { | |
render() { | |
return ( | |
<Provider> | |
<SimpleCount/> | |
</Provider> | |
) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! I like this!
Assuming "Count" should be "SimpleCount"?