Last active
October 1, 2017 20:45
-
-
Save carpeliam/b7c3f73fbacde9398eeec87e14e10463 to your computer and use it in GitHub Desktop.
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'; | |
function fetchIfNecessary(fetchWithProps, hasRequiredProp) { | |
function mapDispatchToProps(dispatch, props) { | |
return { fetch: () => dispatch(fetchWithProps(props)) }; | |
} | |
return (Component) => { | |
class Fetcher extends React.Component { | |
componentDidMount() { | |
if (!hasRequiredProp(this.props)) { | |
this.props.fetch(); | |
} | |
} | |
componentDidUpdate() { | |
if (!hasRequiredProp(this.props)) { | |
this.props.fetch(); | |
} | |
} | |
render() { | |
return hasRequiredProp(this.props) && <Component {...this.props} />; | |
} | |
} | |
const componentDisplayName = Component.displayName || Component.name || 'Component'; | |
Fetcher.displayName = `Fetcher(${componentDisplayName})`; | |
return connect(null, mapDispatchToProps)(Fetcher); | |
} | |
} | |
// fetchIfNecessary((props) => fetchSandwich(props.match.params.id), (props) => !!props.sandwich.id)(Sandwich); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment