Search code examples
reactjsreact-routerreact-router-reduxredux-saga

Access props.location object from redux-saga


My end goal is to access this.props.location.pathname inside redux-saga when making API calls. Here's my current working solution, albeit with react raising an error. I'm using mxstbr/react-boilerplate-brand as my codebase.

In my wrapping component, App, I have the following line in my render method.

render() {
  this.props.onUpdateLocation(this.props.location)
}

In my mapDispatchToProps I have following. Basically I'm just saving this.props.location into the React store:

function mapDispatchToProps(dispatch) {
  return {
    onUpdateLocation: (location) => {
      dispatch(updateLocation(location));
    },
    dispatch,
  };
}

Inside my redux-saga I access the location from state and just use it as need be; however, here's the error React raises.

warning.js:44 Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

I can't put it in componentWillMount because that only gets fired once when the app starts, and I can't put it in componentWillUpdate because this.props.location gets updated in the render method. I can't put it in componentDidUpdate because that's too late.

Am I just missing some easy obvious way to access the react-router location inside my redux-saga?


Solution

  • if you have <Route path='profile' component={ Profile } /> the Profile component can access the react-router props in the second argument ownProps of:

    mapStateToProps(state, [ownProps]) and mapDispatchToProps(dispatch, [ownProps])