What's causing the "* before initialization" error in Vue with TypeScript?

I am encountering an issue with my code where I get the error "Cannot access 'AuthCallback' before initialization" when attempting to call the router function in the AuthCallback component. What could be causing this problem? The desired functionality is as follows: When a user logs in, they should be redirected to the callback page and then immediately to the profile page. However, I keep running into this error whenever 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>

Answer №1

  1. According to the information provided in the documentation located at https://router.vuejs.org/guide/essentials/navigation.html:

When working within a Vue instance, you can access the router instance using $router. This allows you to use this.$router.push.

Therefore, in your user-callback.vue file, you can simply call this.$router.push('/something') without having to import router/index.ts.

  1. Alternatively, you could utilize useRouter():
import { useRouter } from 'vue-router';
const router = useRouter();

router.push('/something')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular with Firebase: How to ignore a field in a query

I am curious to see if my current structure is compatible with Firebase, or if I need to make adjustments. Let's take a look at an example using the "/rooms" endpoint, which contains an array of Room objects: export class Room { id: number; p ...

Adjust the color of the entire modal

I'm working with a react native modal and encountering an issue where the backgroundColor I apply is only showing at the top of the modal. How can I ensure that the color fills the entire modal view? Any suggestions on how to fix this problem and mak ...

How can you assign values to a complex, multi-layered object?

My objective is to store distinct data in an object users: [ { 'names': [], 'addresses': [], } ], I am using checkboxes like this: <input type="checkbox" id="john" value="john" v-model="users.names"> Th ...

Error with Angular 2 observables in TypeScript

When a user types a search string into an input field, I want to implement a debounce feature that waits for at least 300 milliseconds before making a request to the _heroService using HTTP. Only modified search values should be sent to the service (distin ...

What is the process of creating a for loop in FindById and then sending a response with Mongoose?

Is there a way to get all the data in one go after the for loop is completed and store it in the database? The code currently receives user object id values through req.body. If the server receives 3 id values, it should respond with 3 sets of data to th ...

Challenges encountered when using promises for handling mysql query results

I've been working on creating a function that will return the value of a mysql query using promises. Here's what I have so far: query(query: string): string { var response = "No response..."; var sendRequest = (query:string): Prom ...

I am struggling with how to print the value of an object in nativescript-vue. Can anyone help me with

Upon examining the nativescript-vue code provided, I encountered an issue where I am unable to print json.city.value in the Label element. However, I can successfully print it within the script section; specifically inside the readFromJson method using c ...

An error occurs with webpack during postinstall when trying to load TypeScript

I have created a custom package that includes a postinstall webpack script as specified in my package.json file: "scripts": { ... "postinstall": "webpack" } The webpack configuration looks like this: const path = require('path'); ...

Using VueJS to dynamically add a CSS class if a certain filter is

Can you apply this filter rule in VueJS? If an element has the filter discount, the parent will be styled with the class color-green (in this case, the span tag) Check out my JSFIDDLE for more details :) HTML <div id="app"> <h3>50% Disc ...

Having trouble with Vue component not updating Vuex state before it loads?

At times, the token is committed to Vuex store while other times it is not. userLogin() { axios.post('api/login', this.logindata,) .then(response => { let token = JSON.parse(localStorage.getItem('token')); t ...

Obtaining the desired element from a function without relying on an event

Recently, I've been working on a sidebar with several links <sidebar-link href="/dashboard" icon="HomeIcon" :is-active="isActive()" /> <sidebar-link href="/test" icon="TestIcon" :is-active=&qu ...

Exploring the method of implementing a "template" with Vue 3 HeadlessUI TransitionRoot

I'm currently working on setting up a slot machine-style animation using Vue 3, TailwindCSS, and HeadlessUI. At the moment, I have a simple green square that slides in from the top and out from the bottom based on cycles within a for-loop triggered by ...

JavaScript - Imported function yields varied outcome from module

I have a utility function in my codebase that helps parse URL query parameters, and it is located within my `utils` package. Here is the code snippet for the function: export function urlQueryParamParser(params: URLSearchParams) { const output:any = {}; ...

Dividing an array into categories with typescript/javascript

Here is the initial structure I have: products = [ { 'id': 1 'name: 'test' }, { 'id': 2 'name: 'test' }, { 'id' ...

Is there a more effective way to implement a Custom Validator using .forEach?

I have developed my own validation class as a learning exercise. Do you think this is an effective approach, or do you have suggestions for improvement? import { AbstractControl } from '@angular/forms'; export class ProjectNameValidator { pr ...

Can Vue.js 3 composition be leveraged with v-for to incorporate a query string into a router-link?

I have successfully implemented v-for for a URL path. Now, I am looking to merge the URL path with the query string in the router link tag. The query string will be the date from each item rendered by v-for. Is there a way to dynamically pass this query ...

Clarifying the concept of invoking generic methods in TypeScript

I'm currently working on creating a versatile method that will execute a function on a list of instances: private exec<Method extends keyof Klass>( method: Method, ...params: Parameters<Klass[Method]> ) { th ...

Utilize VUE components for rendering v-html

I'm currently working on developing a unique VUE component preview feature, reminiscent of JSFiddle or CodePen, within the VUE framework. The specific VUE container responsible for previewing the components is outlined as follows: <quickpreview v- ...

Vue and Axios encountered a CORS error stating that the 'Access-Control-Allow-Origin' header is missing on the requested resource

I've encountered the error above while using Axios for a GET request to an external API. Despite consulting the Mozilla documentation, conducting thorough research, and experimenting with different approaches, I haven't made any progress. I&apos ...

Learn how to showcase specific row information in a vuetify data table on Vue.js by implementing icon clicks

I am currently working on a Vuetify data table that showcases order information, with an option for users to cancel their orders by clicking on the cancel icon. Upon clicking the cancel icon, a confirmation overlay pops up displaying the specific order id. ...