Search code examples
reactjsreduxredux-router

componentWillReceiveProps not firing on router param change


I am using react-router-redux along with redux, react-router and react and have everything working quite well in this repo:

https://github.com/justsayno/redux-react-introduction-code/tree/issue-branch

(look in branch issue-branch for reproducting my issue)

I have integrated the react-router state into my redux state using react-router-redux and can successfully use mapStateToProps to get the router parameter employeeId I need from the props like so:

(The following is from this file)

const mapStateToProps = (state, ownProps) => ({ 
    employeeId : ownProps.params.employeeId,
    employee: state.selectedEmployee.item,
    hasLoaded: state.selectedEmployee.hasLoaded,
    hasError: state.selectedEmployee.hasError,
    error: state.selectedEmployee.error
})

In my render function I can console.log(The employeeId is ${this.props.employeeId}) and it changes as I route to that component and the params change.

But for reasons I do not understand this does not fire when the params change.

componentWillReceiveProps(nextProps){
    console.log(nextProps)
}

What I am trying to achieve is a differnet mock API call for the list of employees vs the single employee and I need to re-retrieve the employee when the employeeId param changes or else I only see one of the employees. I was going to do this in my componentWillReceiveProps function, check the employeeId for changes and kick off an action if it has like so:

componentWillReceiveProps(nextProps){
    const { employeeId, selectEmployee } = this.props
    if(nextProps.employeeId !== employeeId){
        selectEmployee(nextProps.employeeId)
    }
}

Am I just approaching this wrong?


Solution

  • componentWillReceiveProps fires only when props changes. In your case you have initial props with employeeId set and doesn't change. You can reach employeeId in componentWillMount.

    And the problem with your selectEmployee call is that it doesn't dispatch employeeSelected, because hasLoaded is set once to true in EMPLOYEE_RECEIVED action and later never change, so selectEmployee returns before dispatching employeeSelected, which suppose to change hasLoaded back to false in EMPLOYEE_SELECTED.