Created
October 3, 2017 08:10
-
-
Save bultas/5c85fa56f45cf6ab5165554468ea7dc6 to your computer and use it in GitHub Desktop.
Redux FetchAndConnect
This file contains hidden or 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 'react-redux'; | |
class FetchComponent extends React.Component { | |
constructor() { | |
super(); | |
this.state = { | |
dataFetched: false | |
}; | |
} | |
componentWillMount() { | |
const { getter, dispatch } = this.props; | |
dispatch(getter).then(() => { | |
this.setState({ | |
dataFetched: true | |
}); | |
}); | |
} | |
render() { | |
const { Component, getter, ...rest } = this.props; | |
if (this.state.dataFetched) { | |
return <Component {...rest} />; | |
} | |
return null; | |
} | |
} | |
FetchComponent.propTypes = { | |
getter: React.PropTypes.func.isRequired, | |
dispatch: React.PropTypes.func.isRequired, | |
Component: React.PropTypes.func.isRequired | |
}; | |
const Fetch = connect()(FetchComponent); | |
export const fetchAndConnect = (getter, ...connectArgs) => Component => { | |
return () => | |
<Fetch | |
getter={getter} | |
Component={connect(...connectArgs)(Component)} | |
/>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment