Let's say I have a react component like this:
const MyComponent = ({data}) => (<div>{JSON.stringify(data)}</div>);
const myReduxSelector = (state, id) => state.someData[id];
export default connect(
(state, ownProps) => ({
data: myReduxSelector(state, ownProps.someId)
})
)(MyComponent);
Now this works fine, if the data already exists.
What's the tidiest way to handle this, if the data doesn't already exist?
The only way I can really see to to this, to add an onMount/construct function to dispatch an action that will fetch it.
eg.
class MyComponent extends React.Component {
constructor(props) {
super(props);
if (!props.data) {
this.props.fetchData();
}
}
render() {
const {data} = this.props;
return <div>{JSON.stringify(data)</div>;
}
}
export default connect(
(state, ownProps) => ({
data: myReduxSelector(state, ownProps.someId)
}),
(dispatch, ownProps) => ({
fetchData: () => dispatch(createFetchDataAction(ownProps.someId))
})
)(MyComponent);
The problem with this is - say I have lots of components that all do this, it just becomes a pain to write and maintain.
Is there a tidy, established pattern for solving this problem? Use of redux-saga is acceptable.