Last active
May 22, 2017 09:33
-
-
Save marcusradell/9caa9071320be3b3208cabd03862d337 to your computer and use it in GitHub Desktop.
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
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 />; | |
}); |
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
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 }); |
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
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