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

Developing the headers for a service using React.js

As someone new to ReactJs, I'm curious about the various methods we can use to include Headers in our service Url before making a call. While I'm familiar with how GET/POST Calls are made in angular Js after including headers, I'd like to l ...

Generate an instance containing attributes that correspond to constant string values within a class

In the world of TypeScript, I have a scenario that might be a bit tricky, but I'll throw it out there anyway. Let's say I start with a base service class: export default class Service { public static readonly accessorName: string constructo ...

Is it possible to create a distinctive property value within an ngFor loop that operates autonomously across two child components?

I am working on a functionality where, upon clicking on a specific car brand, the name of the person and their favorite car will be displayed at the bottom. However, I'm facing an issue where the car brand is being repeated among all items in the ngFo ...

What steps do I need to take to integrate the turn.js JavaScript library with a Vue.js and Laravel project?

I am a Vuejs beginner currently working on a project that involves both Vuejs (front end) and Laravel (Backend). I have been trying to integrate the JQuery library turn.js into my project, but I keep encountering errors. While I have managed to run jQuery ...

Typescript: Declaring object properties with interfaces

Looking for a solution to create the childTitle property in fooDetail interface by combining two properties from fooParent interface. export interface fooParent { appId: string, appName: string } export interface fooDetail { childTitle: fooParent. ...

Change the parent title attribute back to its original state

This is in contrast to queries similar to the one referenced here. In my scenario, there is a child element within a parent element (specifically a matSelect within a matCard, although that detail may not be significant) where the parent element has a set ...

Show image using Typescript model in Angular application

In my Angular (v8) project, I have a profile page where I typically display the user's photo using the following method: <img class="profile-user-img" src="./DemoController/GetPhoto?Id={{rec.Id}}" /> However, I am considering an alternative ap ...

Exploring ways to incorporate conditional imports without the need for personalized webpack settings!

Our project is designed to be compatible with both Cordova and Electron, using a single codebase. This means it must import Node APIs and modules specific to Node for Electron, while ignoring them in Cordova. Previously, we relied on a custom webpack con ...

Instructions for automating the clicking of a Vue/Vuetify card using Selenium with Python

Currently, I am utilizing selenium version 4.0.0 for my project. I encountered a challenge while attempting to click on a Vuetify card element serving as a button. However, I kept encountering errors such as element not interactable: [object HTMLDivElemen ...

When working with Vue JS, which is more performant and preferable to use: making direct changes to state in Pinia or using $patch()?

Hey guys, I've been working with Pinia and Vuejs 3, and I'm curious about the performance impact of using $patch(). Can anyone shed some light on this? What is considered the best practice when it comes to this situation? For instance, take a l ...

Why does the error "property undefined" keep popping up even though I've already declared it?

Currently, I am facing an issue with toggling the theme in my project. I am encountering difficulties with the types involved, and I am unsure whether the problem lies within my TypeScript configuration or my actual code itself. I attempted to replicate t ...

Obtaining the Froala text editor's instance in React: A step-by-step guide

Is there a way to access the Froala editor instance within my React components? I've noticed that the official Froala documentation doesn't provide instructions for achieving this in React, only in jQuery. ...

Error: The window object is not defined in NextJS

I've encountered an issue while trying to build the app for production. The error message states: ReferenceError: window is not defined. I'm struggling to find a solution. FullCode: const [windowSize, setWindowSize] = useState<WindowInfo>( ...

Issue with updating Angular list reference when deleting an item

My current task involves implementing a feature that displays selected items from a hierarchical structure on the right side. slice.component.ts : import { Component, Input, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core&a ...

Error message "After the upgrade to Angular 15, the property 'selectedIndex' is not recognized in the type 'AppComponent'."

My Ionic 6 app with capacitor has been updated in the package.json file. These are the changes: "dependencies": { "@angular/common": "^15.1.0", "@angular/core": "^15.1.0", "@angular/forms": "^15.1.0", "@angular/platform-browser": "^15.1. ...

Angular 2 TypeScript: The concat() function operates as mutable within the framework

When I declare an array on an @Injectable provider, my intention is to use it across different components. normeList: any[] = [ { name: 'choice 1', type:'false' }, { name: 'choice 2', typ ...

Retrieving various properties of an object by matching IDs and displaying them without repeated reductions

I'm interested in finding a more efficient way to retrieve properties from a reduced object within a Vue component or wrapper DOM element. Let's say I have these two data objects in my component: player: [{ active: true, id: 0, name: &q ...

Class with abstract properties that are defined by its child classes

Is there a way to use TypeScript's abstract class to enforce defining functions and variables within the class for implementation? abstract class Animal { sound: string; speak() { console.log(this.sound); } } class Cat extends Animal { s ...

What is the best way to dynamically change the main content based on the sidebar option chosen in a React application?

Currently, I am in the process of creating the layout for the page similar to the image provided. When a user selects option A from the sidebar, my goal is to display the corresponding content on the same page without navigating to a new one. This projec ...

Issue with importing Bootstrap-vue components when importing an npm package locally

Maybe I'm overcomplicating things, but here's the issue I'm facing: When I publish my project (my-navigation) to the npm registry and then npm install it in another project (my-vue-app), everything works perfectly. However, if I try to npm ...