Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to reset react-router on page reload

using "react-router": "^3.0.2",

When I do a page reload I need it to go to the default view, which it is currently doing. However, the actual route that is in the history is still the same as the one from where I did the refresh at. So that component is remounting when it shouldn't be.

routing history

    export const browserHistory = useRouterHistory(useBeforeUnload(createHistory))()

routes

 <Router history={browserHistory}>
    <Route path='/' name='Auth' component={Auth}>
      <IndexRoute
        component={Dashboard}
        onEnter={(nextState, replace) => replace('/login')} />
      <Route path='dashboard' name='Dashboard' component={Dashboard} />
      <Route path='resources' name='Resources' component={Resources} />
      <Route path='users' name='Users' component={UsersContainer} />
      <Route path='user/:params' name='User' component={UserContainer} />
    </Route>
    <Route path='/' name='NoAuth' component={NoAuth}>
      <Route path='login' name='Login Page' component={Login} />
    </Route>
  </Router>

This is how I check to see if the user still has a valid session token, and how I reroute to the dashboard. Not sure if I am doing this the best way.

    const _checkAuth = () => {
  if (profile) {
    const res = JSON.parse(profile)
    store.dispatch({ type: types.LOGIN_IDENTITY_SUCCESS, res })
    console.log(browserHistory.getCurrentLocation().pathname)
    router.replace('/dashboard')
  }
}

_checkAuth()
like image 830
texas697 Avatar asked Oct 18 '22 16:10

texas697


1 Answers

if you want to push onto a new route with react-router you can use the .push method to push another route onto the stack, this won't remove the first route in the history if that's what you are looking for, but it will correctly push the new route into react-router

const _checkAuth = () => {
  if (profile) {
    const res = JSON.parse(profile)
    store.dispatch({ type: types.LOGIN_IDENTITY_SUCCESS, res })
    console.log(browserHistory.getCurrentLocation().pathname)
    browserHistory.push('/dashboard');
  }
}

_checkAuth()

Just replace router.replace('/dashboard') with browserHistory.push('/dashboard')

like image 141
Thomas Freeborough Avatar answered Oct 20 '22 23:10

Thomas Freeborough