Closed
Description
Hi, when my app start, beforeEnter is fired twice, dunno why. And since i'm using socket, after this all my sockets emit twice. Am I missing something ?
I'm using vue 2.
UPDATE: this seems to occur because of asynchronous calls in my function.
See this fiddle: https://jsfiddle.net/1xb99hz6/
This is my code :
import Vue from 'vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import socket from './services/socket'
import {auth} from './services/auth'
// import vue componenets
import App from './routes/app.vue'
import Signin from './routes/signin.vue'
import Signup from './routes/signup.vue'
// init all the things
Vue.use(VueRouter);
Vue.use(VueResource);
Vue.use(socket.install);
// config routes
const router = new VueRouter({
base: __dirname,
linkActiveClass: 'active-link',
routes: [
{ path: '/', beforeEnter: auth, component: App},
{ path: '/signin', component: Signin },
{ path: '/signup', component: Signup }
]
});
// mount a root Vue instance
new Vue({
router,
}).$mount('#app');
And my auth function :
function auth(to, from, next) {
console.log('in auth');
// if no internet connection
if (!navigator.onLine) {
next('/nointernet');
}
const jwt = getToken();
if (jwt) {
// send the jwt
socket.emit('authenticate', {token: jwt}) ;
// if user is authenticated
socket.once('authenticated', (token) => {
next();
});
// if user is unauthorized
socket.once('unauthorized', () => {
removeToken(tokenKey);
next('/signin');
});
} else {
next('/signin');
}
}
in console I get 'in auth' twice in a really short amount of time.