Should mapDispatchToProps dispatch initialization actions?

Suppose a stateless, functional UserProfile

component renders user data for a given URL. Let's say it's wrapped with connect(mapStateToProps, mapDispatchToProps)(UserProfile)

. Finally, suppose the reducer reduces to state.userProfile

. Anytime the url changes I need to reinitialize state.userProfile

, so the solution that comes to mind is to do it inside mapDispatchToProps like so:

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

      

Assuming thunked fetchUser ignores repeated calls over the current state, is this an acceptable practice? Or is there a problem with calling dispatch immediately from this map function?

+2


source to share


1 answer


This is unsupported and can be interrupted 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 to do so:



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)
    }
  }

  // ...

}

      

+5


source







All Articles