Xeperis
Xeperis

Reputation: 1459

Dispatching action on Route change

I have a smart User component that renders user information from Redux state.

Here is a route I defined:

<Route path="/users/:id" component={User}/>

Whenever I click on a specific user, route changes and it forces component to update. However when route changes I wish to dispatch a Redux action to fetch user details by :id from an external API.

What is the correct approach of fetching new set of data for User component after changing Route path?

I have tried to dispatch Redux action on componentWillReceiveProps() but this causes infinite loop since the action causes component to update again... repeat.

Upvotes: 1

Views: 474

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281626

You can do that in componentWillReceiveProps but there you can provide a condition on present and nextProps like

componentWillReceiveProps(nextProps) {

    if(this.props.params.id !== nextProps.params.id) {
        //...action here 
    }
}

Upvotes: 3

Related Questions