Exploring the new features of VueJS 3 with Typescript

Just starting out on my first project using typescript and encountering some interesting challenges.

In my Login.vue file, I have the following method:

 const doLogin = async () => {
      try {
        const { email, password } = credentials.value;
        console.log(credentials.value)
        await state.login(email, password).then(()=>{
          console.log(state.dashboardData.value)

          router.push({path : "/dashboard/"+state.dashboardData.value[0].hashCode, replace: true });
        });
        
        
      } catch (error) {
        console.log(error);
        handleAlert(error.error, true);
      }
    };

The state.login function is defined in auth.ts. The login process itself works fine; you can see that I make a second API call immediately after logging in to retrieve a list of dashboard services. This call also works well and saves the data to the store. However, the problem I'm facing (on this page and another) is that the state.dashboardData is only accessible after manually refreshing the page.

  const login = (email: any,password: any) =>{
        const url = process.env.VUE_APP_API_URL+'/authentication_token'
        return new Promise((resolve, reject) => {
            axios
          .post(url, {email:email,password:password})
          .then(response => {
              console.log(response.data.token)
            state.token=response.data.token
            state.initialized=true
            state.user=true

            const urlDash = process.env.VUE_APP_API_URL + '/api/dashboards'
            const config = {
                headers: { 'Authorization': 'Bearer '+response.data.token }
            };
      
                  axios
                .get(urlDash,config)
                .then(response => {
                    console.log(response)
                  state.dashboardData=response.data['hydra:member']
                })
            

            resolve(state)
          })
          .catch(() => {
            state.error= 'Incorrect username or password'
            reject(state)
          })
        })
    }

Answer №1

After inserting additional console.log statements, I noticed that the function was returning before receiving a response. By adding await, I was able to resolve this issue. While I am not certain if this is the best solution, it did work in this case.

const authenticateUser = async(email: any,password: any) =>{
        const url = process.env.VUE_APP_API_URL+'/authentication_token'
        return new Promise((resolve, reject) =>  {
            axios
          .post(url, {email:email,password:password})
          .then(async(response) => {
              console.log(response.data.token)
            state.token=response.data.token
            state.initialized=true
            state.user=true

            // const jwt: {email: any}=jwtDecode(response.data.token)
            // state.email=jwt.email
                
            //fetch dashboard data
            const urlDash = process.env.VUE_APP_API_URL + '/api/dashboards'
            //console.log(store.token.value)
            const config = {
                headers: { 'Authorization': 'Bearer '+response.data.token }
            };
      
            //console.log(config)
            
                  await axios
                .get(urlDash,config)
                .then(response => {
                    console.log(response)
                  state.dashboardData=response.data['hydra:member']
                })
            

            resolve(state)
          })
          .catch(() => {
            state.error= 'Incorrect username or password'
            reject(state)
          })
        })
    }

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

Embracing Typescript version 2.7 and above allows for utilizing multiple types within a parameter, enabling developers to efficiently handle specific properties

Imagine a scenario where a ChildClass is extending the ParentClass. You can view the code on Stackblitz here. The ChildClass simply adds a public property called "brainPower": class ParentClass{ _me: string; constructor() { this._me = "I'm ...

Generate user-customized UI components from uploaded templates in real-time

Summary: Seeking a solution to dynamically generate UI pages using user-provided templates that can be utilized for both front-end and back-end development across various use cases. Ensuring the summary is at the top, I am uncertain if this question has b ...

The 'setComputed' property is not mandatory in the type definition, however, it is a necessary component in the 'EntityExample' type

I'm encountering an issue while trying to create a factory for updating an entity. The error I'm facing is related to the usage of afterload: Entity: import { Entity, PrimaryGeneratedColumn, Column, OneToMany, BaseEntity, AfterLoad, ...

Error: Invalid character '&' after initializing create-t3-application bootstrap

After initiating a new next.js app with the command npm create t3-app@latest, I encountered an unexpected syntax error when running the app using npm run dev. The error displayed was SyntaxError: Unexpected token '??='. Additionally, my console o ...

Having issues with using the class selector in SVG.select() method of the svg.js library when working with TypeScript

Exploring the capabilities of the svg.js library with typescript has presented some challenges when it comes to utilizing CSS selectors. My goal is to select an SVG element using the select() method with a class selector. In this interactive example, this ...

Animation on React child component disappears when re-rendered

My React application utilizes Material UI with a component (let's call it DateSelector) as shown below, slightly altered for demonstration purposes. https://i.sstatic.net/RlPZa.gif Material UI provides animations for clicks and interactions within i ...

Find all objects in an array that have a date property greater than today's date and return them

I have an array of objects with a property called createdDate stored as a string. I need to filter out all objects where the createdDate is greater than or equal to today's date. How can this be achieved in typescript/javascript? notMyScrims: Sc ...

"Encountering a problem with 'never' type in Angular 12 and Types

Currently, working with Angular 12 but encountering an issue with the following code snippet. this.recorder.ondataavailable = (event: { data: any; }) => { this.recordedChunks.push(event.data); }; Here is the error thrown by Typescript: Argument of ty ...

The functionality of VisualCode IntelliSense Jasmine Typings appears to be malfunctioning

After setting up jasmine typings in my project and saving them in the "index.d.ts" file, I encountered an issue when using expect('').toBeNaN in my tests. Only "toBe" was being displayed, nothing more. Below are the configuration files I am usin ...

Organizing Telephone Number Entries in Angular

In my search for a way to format a phone number input field in Angularjs, I have come across many solutions, but none specifically for Angular 7. What I am looking to achieve is for the user to enter the textfield like so: 123456789 and have the textfi ...

Is there a mistake in how I am creating this TypeScript object?

After selecting an item from a dropdown menu, I want to remove the select element and display the selected item in an ag-grid. Although the row is added to the grid successfully, the name/id properties do not appear correctly and the select element remains ...

Remapping compound enum-like constant objects dynamically with type safety in TypeScript

I am currently developing a small utility that generates typesafe remapped object/types of compound enums. The term "compound" in this context refers to the enum (essentially a const object) key mapping to another object rather than a numeric or literal va ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...

"Exploring the depths of Webpack's module

This is my first venture into creating an Angular 2 application within MVC Core, utilizing TypeScript 2.2, Angular2, and Webpack. I have been closely following the Angular Documentation, but despite referencing the latest NPM Modules, I encounter errors w ...

Is Typescript compatible with the AWS Amplify Express API?

I've been struggling to set up my Amplify API in TypeScript and then transpile it to JavaScript. I know it sounds like a simple process, but I could really use some guidance on how to do this effectively. So far, I haven't progressed beyond the ...

Checking the next route in Angular 2 when navigating away

Is there a way to trigger an action only on specific NavigationEnd router events, excluding when navigating between child routes or on a particular route? This is a snippet from my app.routing.ts: // other route configurations... { path: 'scrapers/ ...

Insight into Typescript types through dot notation

Here is the interface I am working with: export interface IRenderStruct { type: string; props: { className?: string; children?: (string | IRenderStruct) | (string | IRenderStruct)[]; [propName: string]: any; }; } The objects created bas ...

The error code TS2322 indicates that the type 'string | null' cannot be assigned to the type 'number'

I am completely new to both Angular and TypeScript, so I'd like to start by mentioning that. In my Angular program, I have implemented routing to display more information on a separate page. The errors are occurring within the ngOnInit() method: Th ...

Array of the Unknown

public loadFiles(event: Event) { let files = event.target['files']; let fileList: string[]; console.log(files); for (var i = 0; i < files.length; i++) { if (FileReader && files && files.length) { let fileReader = ...

TypeScript definition for string representations of a combined type of numbers

I am exploring ways to create a TypeScript type that restricts values to specific string representations of numbers. Let's dive into the details: Imagine having a union numeric type defined like this: const ONE = 1; const TWO = 2; type ALLOWED_NUMBE ...