Search code examples
reactjsreact-routerreact-router-redux

Actions as callbacks in react-router routes components


I would like to use a redux action as callback to the onChange event in the react-router route. I am also using the react-router-redux.

Something like

<Route path="profile/search" component={ProfileSearch} onChange={store.dispatch(fetchCompanies())} />

where fetchCompanies is the action.

More generally, I would like the to listen to a route change and ultimately interact with the state, that is why using an action seems like the most straightforward option to me. However, I get this error:

Uncaught TypeError: hook.apply is not a function TransitionUtils.js?f913:22

Is there another way to achieve this? Is trying to pass an action as a callback to the route change inherently bad? If not, how can I make it work?


Solution

  • Calling store.dispatch throws the error, but wrapping the dispatched action in a function works.

    const onChangeProfileSearch = () => store.dispatch(fetchCompanies());
    <Route path="profile/search" component={ProfileSearch} onChange={onChangeProfileSearch} />
    

    However, there may be a better approach to this.