Search code examples
typescriptvue.jsvue-router

Vue+TS Cannot access * before initialization?


Getting the error Cannot access 'AuthCallback' before initialization when I call the router function in AuthCallback component, what's wrong? The functionality what i need is - When the user logs in, he is transferred to the callback page, and immediately after to the profile page, but this is the error I get if I try to connect my router

router.ts

import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import main from '../layout/main-layout.vue'
import AuthCallback from '../components/user/user-interact/user-callback.vue'
import Profile from '../components/user/user-profile/user-profile.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'main',
      component: main
    },
    {
      path: '/callback/:',
      name: 'AuthCallback',
      component: AuthCallback
    },
    {
      path: '/id/:usedId',
      name: 'Profile',
      component: Profile
    }
  ]
})

export default router

user-callback.vue

<script lang="ts">
    import { useRoute } from 'vue-router';
    import router  from '../../../router/index.ts';
    import { store } from '../../../stores/userState.ts'
    
    export default {
        name: 'AuthCallback',
        mounted() {
            const tokenParseRegex: RegExp = /access_token=(.*?)&/;
            const idParseRegex: RegExp = /user_id=(.*?)$/;
            const exAccessToken: RegExpMatchArray | null = useRoute().hash.match(tokenParseRegex);
            const exUserId: RegExpMatchArray | null = useRoute().hash.match(idParseRegex);
            if (exAccessToken![1] !== null) {
                store().userState.accessToken = exAccessToken![1];
                store().userState.userId = exUserId![1];
                store().userState.isAuthorized = true;
            } else {
                return
            }
            if (store().userState.accessToken !== null) {
                    console.log(router()) // if i remove this line - all be fine
            }
        }   
    }
</script>

Solution

    1. As mentioned in the docs https://router.vuejs.org/guide/essentials/navigation.html :

    Inside of a Vue instance, you have access to the router instance as $router. You can therefore call this.$router.push.

    So, in your user-callback.vue, without importing router/index.ts, just call this.$router.push('/something')

    1. Or, you can use useRouter():
    import { useRouter } from 'vue-router';
    const router = useRouter(); 
    
    router.push('/something')