6

I am trying to drive my application's navigation from its state. Here's my use case:

Given the user is on the Login page
When the application state changes to isLoggedIn
Then the application should navigate to the Dashboard page

Here's my current implementation which works:

if (browserHistory.getCurrentLocation().pathname === '/login' && store.isLoggedIn) {
    browserHistory.push('/dashboard');
}

Unfortunately going through react-router docs and issues, I understand that browserHistory.getCurrentLocation() is not an official API and it should not be used. Is there a recommended way to do this?

P.S. This code is running outside a React component, so I cannot use this.props.location.pathname

Naresh
  • 23,937
  • 33
  • 132
  • 204

1 Answers1

0
export const onAuthChange = (isAuthenticated) => {
  const pathname = browserHistory.getCurrentLocation().pathname;
  const isUnauthenticatedPage = unauthenticatedPages.includes(pathname);
  const isAuthenticatedPage = authenticatedPages.includes(pathname);

  if (isUnauthenticatedPage && isAuthenticated) {
    browserHistory.replace('/Dashboard');
  } else if (isAuthenticatedPage && !isAuthenticated) {
    browserHistory.replace('/');
  }

};
  • 2
    It is often useful to other users if you explain your answer. In the future your answer may help others in unexpected ways but that is less likely if it is just a block of code. – Brody Jul 19 '17 at 05:32