Skip to content

Instantly share code, notes, and snippets.

@marcusradell
Last active May 22, 2017 09:33
Show Gist options
  • Save marcusradell/9caa9071320be3b3208cabd03862d337 to your computer and use it in GitHub Desktop.
Save marcusradell/9caa9071320be3b3208cabd03862d337 to your computer and use it in GitHub Desktop.
import React from "react";
import { storiesOf } from "@kadira/storybook";
import Component from "./toggle-button";
storiesOf("toggle-button").add("default", () => {
const { View, stateStream, actions } = Component();
return <View />;
});
import React from "react";
import Connect from "../connect";
const initialState = {
isActive: false
};
const toggle = state => Object.assign({}, state, { isActive: !state.isActive });
const updaters = {
toggle
};
const PureView = ({ state, actions }) => (
<input type="checkbox" value={state.isActive} onChange={actions.toggle} />
);
export default () => Connect({ initialState, updaters, PureView });
import React, { Component } from "react";
import Rx from "rxjs";
export default function create({ initialState, updaters, PureView }) {
const updaterStream = new Rx.Subject();
const stateStream = updaterStream
.startWith(initialState)
.scan((state, updater) => updater(state));
const actions = Object.keys(updaters).reduce(
(accumulator, key) =>
Object.assign({}, accumulator, {
[key]: () => updaterStream.next(updaters[key])
}),
{}
);
class View extends Component {
componentDidMount() {
this.subscription = stateStream.subscribe({
next: state => {
this.setState(() => state);
}
});
}
componentWillUnmount() {
this.subscription.unsubscribe();
}
render() {
return this.state && <PureView state={this.state} actions={actions} />;
}
}
return { View, stateStream, actions };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment