0

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.

1

Sounds like a typical scenario for HOC (higher-order-component) or RenderProps if you prefer it that way. The component would receive the action type that needs to be fired and does so on it's componentWillMount.

Though it's 2019, so a custom effect (React Hook) that dispatches the action from a FunctionalComponentwould probably be the way to go with the current setup based on the information you provided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.