Skip to content

Instantly share code, notes, and snippets.

@antsmartian
Last active June 29, 2018 10:14
Show Gist options
  • Save antsmartian/4f46a70343ba6b9ef4109a7ab944189e to your computer and use it in GitHub Desktop.
Save antsmartian/4f46a70343ba6b9ef4109a7ab944189e to your computer and use it in GitHub Desktop.
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>
)
}
}
@antsmartian
Copy link
Author

@tedlin182: Yeah :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment