24

The only working method that I found to work this out without using react-router-redux to route from action creator async action completion is by passing the history prop from the component to action creator and doing:

history.push('routename');

Since BrowserRouter ignores the history prop passed to it thus we cannot use custom history objects with browserhistory.

What is the best possible way to work this out?

Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318
Jitin Maherchandani
  • 489
  • 1
  • 5
  • 14

1 Answers1

38

Instead of using BrowserRouter you could use the Router with custom history like

import { Router } from 'react-router'

import createBrowserHistory from 'history/createBrowserHistory'

export const history = createBrowserHistory()

<Router history={history}>
  <App/>
</Router>

in which case your history.push() will work. With BrowserRouter history.push doesn't work because Creating a new browserHistory won't work because <BrowserRouter> creates its own history instance, and listens for changes on that. So a different instance will change the url but not update the <BrowserRouter>.

Once you create a custom history, you can export it and then import it in your action creator and use it to navigate dynamically like

import { history } from '/path/to/index';

const someAction = () => {
    return dispatch => {
        ApiCall().then((res) => {
            dispatch({type: 'SOME_CALL', payload: res })
            history.push('/home');
        })
    }
}
Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318
  • 1
    `history` also contain the `location` (`history.location.pathname`), very useful to redirect base on current url. – Hugo Gresse Aug 08 '19 at 08:13
  • With this solution, importing history object to action creator I'm getting an error `TypeError: "_routing__WEBPACK_IMPORTED_MODULE_3__.default.push is not a function"` – ann.piv May 09 '20 at 12:02
  • @ann.piv Are you sure you have exported history as a default – Shubham Khatri May 09 '20 at 12:03
  • Yes it's default export. History object is imported in actions file, but I'm getting an error when calling history.push – ann.piv May 09 '20 at 12:07
  • @ann.piv Can you create a post with more details about its usage and creation – Shubham Khatri May 09 '20 at 12:07
  • Here is the link to my post https://stackoverflow.com/questions/61686352/react-redux-redirect-after-object-is-created-using-new-object-id-in-url – ann.piv May 09 '20 at 12:25