Bijou Trouvaille Bijou Trouvaille - 7 months ago 123
Javascript Question

Should mapDispatchToProps dispatch initialization actions?

Suppose a stateless, functional

UserProfile
component that displays user data for the given url. Suppose it is being wrapped with
connect(mapStateToProps, mapDispatchToProps)(UserProfile)
. Finally, suppose a reducer that reduces into
state.userProfile
. Anytime the url changes, I need to re-initialize the
state.userProfile
, so a solution that comes to mind is to do so from within the mapDispatchToProps like so:

function mapDispatchToProps(dispatch, ownProps) {
dispatch(fetchUser(ownProps.userId))
return {
...
}
}


Provided that the thunked fetchUser ignores repeated calls by comparing with current state, is this an acceptable practice? Or are there problems associated with calling dispatch immediately from this map function?

Answer

This is unsupported and can break at any time.
mapDispatchToProps itself should not have side effects.

If you need to dispatch actions in response to prop changes, you can create a component class and use lifecycle methods for this:

class UserProfile extends Component {
  componentDidMount() {
    this.props.fetchUser(this.props.id)
  }

  componentDidUpdate(prevProps) {
    if (prevProps.id !== this.props.id) {
      this.props.fetchUser(this.props.id)
    }
  }

  // ...

}