kitze / mobx-router

A simple router for MobX + React apps
509 stars 66 forks source link

undefined store after goTo #60

Closed kennir closed 6 years ago

kennir commented 6 years ago

I want go to auth page if not authenticated automatic, then go to home page if already authenticated

my views looks like

const views = {
    home: new Route({
        path: '/',
        component: <Home />,
        beforeEnter: (route, param, store) => {
            const isAuthenticated = store.user.isAuthenticated
            if (!isAuthenticated) {
                console.log("not authenticated")
                store.router.goTo(views.auth)
            }
            return isAuthenticated
        }        
    }),
    auth: new Route({
        path: '/auth',
        component: <Auth />, 
        beforeEnter: (route, param, store) => {
            const isAuthenticated = store.user.isAuthenticated
            if (isAuthenticated) {
                console.log("already authenticated")
                store.router.goTo(views.home)
            }
            return !isAuthenticated
        }
    })
}

I got an error after goto auth from home, How can I solve it ?

×
Unhandled Rejection (TypeError): Cannot read property 'user' of undefined
Route.beforeEnter
src/router/index.js:21
  18 | path: '/auth',
  19 | component: <Auth />, 
  20 | beforeEnter: (route, param, store) => {
> 21 |     if (store.user.isAuthenticated) {
  22 |         store.router.goTo(views.home)
  23 |     }
  24 | }
View compiled
▶ 11 stack frames were collapsed.
Route.beforeEnter
src/router/index.js:12
   9 | component: <Home />,
  10 | beforeEnter: (route, param, store) => {
  11 |     if (!!!store.user.isAuthenticated) {
> 12 |         store.router.goTo(views.auth)
  13 |         return false
  14 |     }
  15 | }        
View compiled
▶ 22 stack frames were collapsed.
./src/index.js
src/index.js:19
  16 |     router: new RouterStore()
  17 | }
  18 | 
> 19 | startRouter(views, store)
  20 | 
  21 | 
  22 | ReactDOM.render(

Thanks

kennir commented 6 years ago

replace store.router.goTo(views.home) to store.router.goTo(views.auth, param, store) is fine, is it a solution?

kitze commented 6 years ago

Yes