Skip to content

Instantly share code, notes, and snippets.

@iocat
Created November 17, 2018 07:05
Show Gist options
  • Save iocat/0de249ee16229a8585bd9423e88e2ed7 to your computer and use it in GitHub Desktop.
Save iocat/0de249ee16229a8585bd9423e88e2ed7 to your computer and use it in GitHub Desktop.
Simple high order function that connects flyd streams/callback functions to React
// Example
// const counter = flyd.stream()
// const incCounter = () => counter(counter() + 1)
// const FComp = ({counter, incCounter}) => <span onClick={incCounter}> {counter} </span>
// connectStreams ({
// counter,
// incCounter
// })(FComp)
//
export const connectStreams = streams => Component => {
return class extends React.Component{
constructor(props) {
super(props);
this.callbacks = {}
const state = {}
for (const [key, streamOrCb] of Object.entries(streams)){
if (flyd.isStream(streamOrCb)){ // streams
state[key] = streamOrCb()
flyd.on(data => {
this.setState({[key]: data})
}, streamOrCb)
} else if (typeof streamOrCb === 'function') { // callbacks
this.callbacks[key] = streamOrCb
}
}
this.state = state
}
render () {
return <Component {...this.props} {...this.callbacks} {...this.state}/>
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment