Last active
March 3, 2018 20:02
-
-
Save aaronshaf/e2956a2afebd99937bb0e271564c5548 to your computer and use it in GitHub Desktop.
Experiment with managing state with callbags / pipelines
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
const initialState = { count: 0 }; | |
const pipeline = map(([state, data]) => ({ count: state.count + data })); | |
class App extends Component { | |
render() { | |
return ( | |
<CallbagState initialState={initialState} pipeline={pipeline}> | |
{(state, send) => ( | |
<div> | |
<button onClick={send(1)}>Add 1</button> | |
<button onClick={send(2)}>Add 2</button> | |
<div>{state.count}</div> | |
</div> | |
)} | |
</CallbagState> | |
); | |
} | |
} |
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
class CallbagState extends Component { | |
constructor(props) { | |
super(props); | |
this.subject = makeSubject(); | |
this.state = this.props.initialState; | |
pipe( | |
this.subject, | |
this.props.pipeline, | |
subscribe({ | |
next: state => this.setState(state) | |
}) | |
); | |
} | |
handleSend = data => event => { | |
this.subject(1, [this.state, data, event]); | |
}; | |
componentWillMount() { | |
this.subject(2); // terminates | |
} | |
render() { | |
if (this.props.render) { | |
return this.props.render(this.state, this.handleSend); | |
} else { | |
return this.props.children(this.state, this.handleSend); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment