When I log in with user it redirects me to the dashboard as expected. As soon as I log out and try to log in again (even with another user and without refreshing the page) it returns this error in the console:
I only want to redirect the user in the dashboard if authenticated, even if the page doesn't refresh, because I did notice that if I refresh the page, I can log in with no issues.
Please help me if you can. Here is some code:
Login Method
methods: { ...mapActions({ attempt: "auth/attempt", }), submit(credentials) { axios .post("http://127.0.0.1:8000/api/login", credentials) .then((res) => { // console.log(res.data); if (res.data.success) { this.attempt(res.data.token) } if (res.data.errors) { this.loginErrors = res.data.errors; } else { this.$router.push({ name: 'dashboard' }) } }) .catch((err) => { if ( err.name !== "NavigationDuplicated" && !err.message.includes( "Avoided redundant navigation to current location" ) ) { console.log(err); } }); }, },
Dashboard path in router
{ path: '/dashboard', name: 'dashboard', component: DashboardComponent, beforeEnter: (to, from, next) => { if (!store.getters['auth/authenticated']) { return next({ name: 'home' }) } next() } },
Attempt to perform operations in vuex storage
async attempt({ commit, state }, token) { if (token) { commit('SET_TOKEN', token) } // se non c'è if(!state.token) { return } try { await axios.get('http://127.0.0.1:8000/api/user') .then(res => { commit('SET_USER', res.data) }) } catch (e) { commit('SET_TOKEN', null) commit('SET_USER', null) } },
Others from vuex
namespaced: true, state: { token: null, form: null, }, getters: { authenticated(state) { return state.token && state.form }, user(state) { return state.form }, }, mutations: { SET_TOKEN(state, token) { state.token = token }, SET_USER(state, data) { state.form = data }, },
P粉7712333362024-02-22 10:33:46
Update: Should wait for a call to attempt()
, otherwise this.$router.push({ name: 'dashboard' })
(so /dashboard
The guard function on the route) will be called < em> before the call to the /api/user
API completes:
submit(credentials) { axios .post("http://127.0.0.1:8000/api/login", credentials) .then(async (res) => { // console.log(res.data); if (res.data.success) { await this.attempt(res.data.token) } if (res.data.errors) { this.loginErrors = res.data.errors; } else { this.$router.push({ name: 'dashboard' }) } }) .catch((err) => { if ( err.name !== "NavigationDuplicated" && !err.message.includes( "Avoided redundant navigation to current location" ) ) { console.log(err); } }); },
next
is a function that should be called exactly once ( does not return).
Try changing the code in your router to:
{ path: '/dashboard', name: 'dashboard', component: DashboardComponent, beforeEnter: (to, from, next) => { if (!store.getters['auth/authenticated']) { next({ name: 'home' }) } else { next() } } },