Skip to content

Instantly share code, notes, and snippets.

@bultas
Created October 3, 2017 08:10
Show Gist options
  • Save bultas/5c85fa56f45cf6ab5165554468ea7dc6 to your computer and use it in GitHub Desktop.
Save bultas/5c85fa56f45cf6ab5165554468ea7dc6 to your computer and use it in GitHub Desktop.
Redux FetchAndConnect
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