Created
November 17, 2018 07:05
-
-
Save iocat/0de249ee16229a8585bd9423e88e2ed7 to your computer and use it in GitHub Desktop.
Simple high order function that connects flyd streams/callback functions to React
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
// 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