1

I have a Profile component that shows user profile. On route change to user/:userId, the userId query param will be updated in ownProps thanks to react-router-redux and will then be passed into my presentation component:

const mapStateToProps = (state, ownProps) => ({
  userId: ownProps.params.userId,
  user: store.profile.user //null at first, will be updated later
})

At this point, I need to fetch user profile from userId. Where should I do this fetching? Currently I am doing it in componentDidMount

componentDidMount() {
  this.props.fetchProfile(this.props.userId)  //this will dispatch an action to fetch user details and store in `store.profile.user`
}

The downside of this is if user goes from /users/1 to /users/2, componentDidMount wont trigger. How should this be done?

1 Answer 1

1

You also need to call this.props.fetchProfile from your component's componentDidUpdate method, with an (optional) additional check to see if the userId actually changed. Better yet, you should wrap the call of fetchProfile in a separate method, just in case you'd like to skip the call if the userId is null, for example.

fetchProfile() {
  this.props.userId && this.props.fetchProfile(this.props.userId)
}

componentDidMount() {
  this.fetchProfile()
}

componentDidUpdate (prevProps) {
  prevProps.userId !== this.props.userId && this.fetchProfile()
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.