Skip to content

Instantly share code, notes, and snippets.

@aaronshaf
Last active March 3, 2018 20:02
Show Gist options
  • Save aaronshaf/e2956a2afebd99937bb0e271564c5548 to your computer and use it in GitHub Desktop.
Save aaronshaf/e2956a2afebd99937bb0e271564c5548 to your computer and use it in GitHub Desktop.
Experiment with managing state with callbags / pipelines
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>
);
}
}
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