-
-
Save khadorkin/3c0a0d1aa2e358d77a1e5263fcf580f3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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