dagda1 dagda1 - 4 months ago 28
React JSX Question

Correct place to load data in connected redux component

Where is the correct place to load data in a redux component?

Currently I have it this way.

Say I have this container component:

import { loadResultsPage } from '../actions/winratio-actions';

function mapStateToProps(state) {
const {
isFetching,
results
} = state;

return {
isFetching,
results
};
};

export default connect(mapStateToProps, {
loadResultsPage
})(WinRatio);


I then make a call in the wrapped component's
componentWillMount
lifecycle event:

export default class WinRatio extends Component {
componentWillMount() {
this.props.loadResultsPage();
}

render() {
return (
<div>
<h1>Win Ratio</h1>
</div>
);
}
};


Where should this call happen?

Answer

You can do it in your container component. If you use redux you probably use smart\dumb components strategy. Create a container where you use compose function from redux package and you can compose it like this:

export default compose(
  connect(null, { loadData }), //this is your async action
  doOnComponentMount(({props}) => props.loadData()),
)(MyDumbComponent)

and doOnComponentMount is:

function doOnComponentMount(cb) {
  return (Component) => {
    return class extends React.Component {
      componentDidMount() {
        cb(this);
      }

      render() {
        return <Component {...this.props} />;
      }
    }
  }
}