Skip to content

Instantly share code, notes, and snippets.

@threepointone
Created July 28, 2015 07:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save threepointone/8a1dce2ae36618571587 to your computer and use it in GitHub Desktop.
Save threepointone/8a1dce2ae36618571587 to your computer and use it in GitHub Desktop.
a lightweight flux style store as a component
import React from 'react';
export class Sto extends React.Component{
static defaultProps = {
store: x => x
}
state = {
value: this.props.store()
}
dispatch = action => this.setState({
value: this.props.store(this.state.value, action)
})
render(){
return this.props.children(this.state.value, this.dispatch);
}
}
function store(counter = 0, action){
switch(action.type){
case 'inc': return counter + 1;
case 'dec': return counter - 1;
default: return counter;
}
}
export class App{
render(){
return <Sto store={store}>{
(state, dispatch) => <div onClick={() => dispatch({type: 'inc'})}>
clicked {state} times
</div>
}</Sto>;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment