2

I'm using vuex and laravel as backend for my project.
Redirection after signing in is not working. here is my code :

methods: {
    submit () {
      this.$validator.validateAll()
      if (!this.errors.any()) {
        this.$store.dispatch('SIGNIN', this.user)
        this.$router.push({name: 'chat'})
      }
    }
}


For Vuex :

actions: {
    SIGNIN (context, user) {
      context.commit('handleLoader')
      Vue.http.post(apiDomain + signInUrl, user, {headers: getHeaders})
      .then(response => {
        if (response.status === 200) {
          Vue.auth.setToken(response.body.token)
          Vue.auth.setAuth(response.body.user)
          context.commit('handleLoader')
          // context.commit('navigateAfterSignIn')
        }
      })
    }
}

And my mutation

 mutations: {
    signin (state) {
      state.isLoggedIn = true
    }
  }


My routes :

export default new Router({
  routes: [
    {
      path: '/',
      name: 'chat',
      component: Chat,
      meta: {
        forAuth: true
      }
    },
    {
      path: '/signin',
      name: 'signin',
      component: Signin,
      meta: {
        forVisitors: true
      }
    },
    {
      path: '/signup',
      name: 'signup',
      component: Signup,
      meta: {
        forVisitors: true
      }
    }
  ],
  mode: 'history'
})

And my check for routes protections

router.beforeEach(
  (to, from, next) => {
    if (to.matched.some(record => record.meta.forVisitors)) {
      if (Vue.auth.isAuthenticated()) {
        next({
          path: '/'
        })
      } else next()
    } else if (to.matched.some(record => record.meta.forAuth)) {
      if (!Vue.auth.isAuthenticated()) {
        next({
          path: '/signin'
        })
      } else next()
    } else next()
  }
)

How to redirect automatically??
Thanks for your help

Beni
  • 95
  • 2
  • 13

1 Answers1

3

I don't think that the side effect of navigation should be a part of the Vuex store action UNLESS you are 100% certain it will always need to happen as part of this action. Wherever in the application you are doing this from should take care of that navigation. To accomplish this you need to do two things

In your action, return the promise that is the Vue.http thing

Handle success with a .then in the component your are calling this from

//Store action, note Vue.http.post MUST return a thenable (Promise)
SIGNIN (context, user) {
  context.commit('handleLoader')
  return Vue.http.post(apiDomain + signInUrl, user, {headers: getHeaders})
    .then(response => { 
      handleSettingToken(response)
      return response 
    })
  } 
}

//Component

methods: {   
  handleLogin() {
    return store.dispatch(SIGNIN, user)
      .then(response => doNavigationHere(response)   
  }
}
Austio
  • 5,939
  • 20
  • 34
  • it works :) i have used 'Promise'. this is the link http://stackoverflow.com/questions/40390411/vuex-2-0-dispatch-versus-commit – Beni Mar 03 '17 at 06:46