boh
boh

Reputation: 1547

update state when url changes in redux-react

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?

Upvotes: 1

Views: 2006

Answers (1)

Gunther Konig
Gunther Konig

Reputation: 182

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

Upvotes: 1

Related Questions