Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use history.push in action creator with react-router-v4?

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?

like image 571
Jitin Maherchandani Avatar asked Jan 30 '18 05:01

Jitin Maherchandani


People also ask

How do I push to history on my react router?

push() Method. history. push() is another approach where we make use of the history props React Router provides while rendering a component. In other words, this works when the component is being rendered by React Router, bypassing the component as a Component prop to a Route.

How do I find history on react router v4?

Show activity on this post. import {useHistory } from "react-router-dom"; const TheContext = React. createContext(null); const App = () => { const history = useHistory(); <TheContext.


1 Answers

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');         })     } } 
like image 197
Shubham Khatri Avatar answered Sep 21 '22 03:09

Shubham Khatri