So I'm working on a project where I am using Vuex and vue-router. While logging in, currently, the page refreshes the state and reloads the page after clicking on the login button and again goes to /login route. After it receives the data change from watcher, it redirects user to /home path. I want to achieve a loading without going to /login route when receiving data, since it looks weird.
In my store/index.js file, I have this code :
const state = {
user: null,
loading: false
}
const getters = {
user: state => state.user,
loading: state => state.loading
}
const actions = {
me : ({ commit }) => {
commit('setLoading', true)
apolloClient
.query({
query: GET_CURRENT_USER
})
.then(({ data }) => {
setTimeout(() => {
commit('setLoading', false)
// Add user data to state
commit('setUser', data.me)
console.log(data)
}, 500)
})
.catch(err => {
commit('setLoading', false)
console.log(err)
})
},
login: ({ commit }, payload) => {
localStorage.setItem('token', '')
apolloClient
.mutate({
mutation: LOGIN,
variables: payload
})
.then(({ data }) => {
setTimeout(() => {
localStorage.setItem("token", data.login.auth.token)
router.go('/')
VueNotifications.success({ message: 'Welcome !' })
}, 500)
})
.catch(err => {
VueNotifications.error({ message: 'Error' });
})
},
logout : async ({ commit }) => {
Nprogress.start();
// clear user in state
commit('clearUser')
// remove token in localStorage
localStorage.setItem('token', '')
// end session
await apolloClient.resetStore()
// redirect to home - kick users out of private pages
router.push('/session/login')
Nprogress.done();
}
}
const mutations = {
setUser: (state, payload) => {
state.user = payload
},
setLoading: (state, payload) => {
state.loading = payload
},
clearUser: state => (state.user = null)
}
Also, Login.vue is like this :
computed: {
...mapGetters(['loading', 'user'])
},
created() {
this.$store.dispatch('me')
},
watch: {
deep: true,
immediate:true,
user(value) {
if(value) {
this.$router.push('/')
}
}
},
methods: {
loginUser() {
if(this.$refs.form.validate()) {
this.$store.dispatch("login", {
email: this.email,
password: this.password
})
}
}
}
Lastly, main.js is like this that does implementation of vue-router
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!store.getters.user) {
next({
path: '/session/login',
})
} else {
next()
}
} else {
next() // make sure to always call next()!
}
})
Any help is appreciated, thanks !