Skip to content

Instantly share code, notes, and snippets.

@carpeliam
Last active October 1, 2017 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carpeliam/b7c3f73fbacde9398eeec87e14e10463 to your computer and use it in GitHub Desktop.
Save carpeliam/b7c3f73fbacde9398eeec87e14e10463 to your computer and use it in GitHub Desktop.
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