1

I am using react hooks and redux. I have wrapped the App component with BrowserRouter:

ReactDOM.render(
<React.StrictMode>
    <Provider store={store}>
      <BrowserRouter>
    <App />
    </BrowserRouter>
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

and in the App component, I am using useHistory hook to get the history object:

const history = useHistory();

  useEffect(()=>{
    history.listen((location, action) => {
      // clear alert on location change
      dispatch(alertActions.clear());
    });

But i want to access the history object in my action creator file used for login, so that i can do this after login:

history.push('/');

How do I achieve this? do I have to use Router instead of BrowserRouter?

Edit: I had to use Router, instead of BrowserRouter, and it is working now.

vikrant
  • 1,692
  • 1
  • 18
  • 23
  • 1
    Does this answer your question? [How to Access History Object Outside of a React Component](https://stackoverflow.com/questions/44153517/how-to-access-history-object-outside-of-a-react-component) – Pramod Mali Aug 11 '20 at 05:57
  • In your link , the accepted answer suggests using 'Router' , i have already tried that approach and i was facing some issues with routes, so i decided to use BrowserRouter, so there is no way this can be done with BrowserRouter? – vikrant Aug 11 '20 at 05:59
  • 1
    using Router and passing your own history object should be the way to achieve this, what issues were you encountering using Router instead of BrowserRouter? BrowserRouter just obfuscates creating the history object: [https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/BrowserRouter.js](https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/BrowserRouter.js) – Jacob Smit Aug 11 '20 at 06:05
  • @JacobSmit can i use the useHistory hook with Router? – vikrant Aug 11 '20 at 06:06
  • 1
    Yes. `react-router` has it's own implementation of `useHistory()`, I assume `react-router-dom` re-exports the same hook. – Jacob Smit Aug 11 '20 at 06:12
  • `connected-react-router` https://github.com/supasate/connected-react-router – Drew Reese Aug 11 '20 at 06:19

0 Answers0