Strategies for preventing profanity in Typescript within Nuxt 2 implementation

implement user authorization functionality

create the Auth class for authentication handling

    import type { Context } from '@nuxt/types';
    
    export class Auth {
      public ctx: Context;
    
      constructor(ctx: Context) {
        this.ctx = ctx;
      }
    
      async login(data: any): Promise<any> {
        return await this.ctx.app.$projectServices.repository.login(data);
      }
    
      async fetchUser() {
        return await this.ctx.app.$projectServices.repository.getAuthUser();
      }
    }

generate a plugin to inject the global variable $auth

    import { Plugin } from '@nuxt/types';
    
    import { Auth } from '~/services/auth/auth';
    
    const auth: Plugin = (context, inject) => {
      const auth = new Auth(context);
    
      inject('auth', auth);
    };

export default auth;

during Nuxt initialization, check if there is a token in localStorage, and if present, fetch user data

nuxtClientInit plugin

export default async function (context: any) {
  await context.store.dispatch('nuxtClientInit');
}

store implementation

import { getToken } from '~/services/auth/token';

export const actions = {
  async nuxtClientInit({ commit }: any) {
    const token = getToken();
    if (token) {
      commit('auth/setToken', { token });
      await this.$auth
        .fetchUser()
        .then((response: any) => {
          commit('setItem', response);
        })
        .catch((e: any) => {
          if (e.status === 401) {
            commit('auth/clear');
          }
        });
    }
  },
};

error in the store related to this.$auth usage

TS2339: Property '$auth' does not exist on type '{ nuxtClientInit({ commit }: any): Promise ; }'

what is the solution to this issue?

Answer №1

Include the following line in your tsconfig.json under the types array:

"types": [
      "@nuxt/types", 
      "@nuxtjs/auth" // Don't forget this line
    ]

If adding it to the tsconfig fails, manually add the type in types/vue-shim.d.ts:

import { Auth } from 'nuxtjs__auth'

declare module 'vue/types/vue' {
  interface Vue {
    // ...
    readonly $auth: Auth
  }
}

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

Currently, there is a requirement to include past build outcomes in the HTML test report within the playwright

Is there a way to display the previous build status of each test case for every test case? I have been attempting to use test.info() in playwright, but it seems inaccessible from onTestEnd. One option could be to retrieve the previous build data from Jenki ...

Customizable mongoDB database collection

Is there a more efficient way to make calls to different collections based on a function parameter? I'm exploring the possibility and if it's not feasible, I'll handle it case by case. Currently, I have this code and the goal is to have a u ...

Utilizing Axios to pass multiple values through a parameter as a comma-separated list

Desired query string format: http://fqdn/page?categoryID=1&categoryID=2 Axios get request function: requestCategories () { return axios.get(globalConfig.CATS_URL, { params: { ...(this.category ? { categoryId: this.category } : {}) } ...

Error in Vuepress: Attempting to read properties that are not defined (specifically 'match')

I encountered an error while attempting to build my vuepress project. I followed this npm quickstart guide: After adding some pages, everything was functioning correctly with: npm run:dev However, when I tried to generate html to docs/src/.vuepress using ...

Passing an array of objects as properties in React components

My functional component looks like this: function ItemList({ items }: ItemProps[]) { return <p>items[0].name</p> } Here is how I'm creating it: <ItemList items={items} /> The array items contains objects in the format [{name: &ap ...

The Azure GraphQL serverless function encountering an issue with the Cosmos DB connection, displaying an

After developing a serverless GraphQL API function using Azure functions and connecting it to Cosmos DB, I have encountered an issue with "Invalid URL" that has been puzzling me for a week. Despite running the graphql function locally without any problems, ...

Improving the clarity of Jest snapshot test logs using styled from MUI

Currently, I am working with MUI v5 along with styled components and Jest snapshot testing. I am looking for a way to improve the logs generated when a snapshot test fails. Below is an example of the component I am dealing with: const styledProperties = n ...

Custom positioning of Mui Snackbar in V5

I've been attempting to position a Snackbar in the top right corner with some customization for the top property, but I'm struggling to get it to display correctly. Here's what I've tried: import React from "react"; import { ...

The Laravel Posts that were made experienced a setback as the axios request failed to process with a status code

Encountering an issue with Laravel and Vue.js Every time I attempt to send a post request using axios, I am met with a server error 500. {Request failed with status code 500}. axios method: async callApi(method, url, dataObj ){ try { ...

Combining certain key values from two dictionaries based on matching IDs in Angular

I am currently working with two arrays of JSON objects in Angular. Both dictionaries have a key-value pair called "song_id" in common. My goal is to combine the "rating" key-value from the second array into the first array where the song_id matches. Array ...

Guide on implementing router-link within a select option dropdown in a Vue.js application

a.vue <template> <div>hi i am component 1</div> </template> <script> export default { name: "a", }; </script> b.vue <template> <div>hi i am component 2</div> </template> <script> ...

After upgrading to version 8 of the Firebase JS SDK, the "firestore" module (imported as "firebase") could not be located within the "firebase" package

After upgrading the firebase JS SDK from v7 to v8.0.0, I changed my import of firebase as shown below. import * as firebase from 'firebase'; However, attempting to access certain properties resulted in an error message: firebase.firestore.FieldV ...

Establishing an RSS feed (Google shopping) for an online store built on Vue-storefront

I recently launched a Vue-storefront based online store and now I'm looking to set up Google Shopping ads using an RSS feed for my products. However, I've encountered an error message saying "Unexpected token < in JSON at position 0" when tryi ...

Removing background from a custom button component in the Ionic 2 navbar

Q) Can someone help me troubleshoot the custom component below to make it resemble a plus sign, inheriting styling from the <ion-buttons> directive? In my navbar, I've included a custom component: <notifications-bell></notifications-be ...

What is the best way to incorporate additional properties while utilizing useSession in Next.js with TypeScript?

I've encountered an issue while trying to add new properties using useSession() in a TypeScript environment. Although it works on console.log, there is an error related to the type mismatch. The useSession() function typically returns name, email, an ...

Develop a universal function for inserting information into an array within a data set

I need assistance with my Typescript code. I am currently working on a method that pushes data into an array in a mongoose collection. However, the issue I'm facing is that the value is not being passed dynamically to the Key field in the $set operato ...

What is the reason for a class's attributes being considered undefined even after they have been previously set?

Within my code, there is a class called WorkspaceDatabase that stems from the Dynamic Tree Example. I have incorporated some debugging information to gain a clearer understanding of the issue at hand. The Issue: Upon entering the complete() function, an ...

Using Typescript to import an npm package that lacks a definition file

I am facing an issue with an npm package (@salesforce/canvas-js-sdk) as it doesn't come with a Typescript definition file. Since I am using React, I have been using the "import from" syntax to bring in dependencies. Visual Studio is not happy about th ...

Utilize React.useImperativeHandle() for declaring custom types

function App(){ const refEl:React.MutableRefObject<any> = React.useRef(null); // I am uncertain about the appropriate type here. React.useEffect(()=>{ if(refEl.current){ refEl.current.start() } }, []); return <Countdown ref={refEl} ...

Component importing error with Vue-cal

When I tried to install npm i vue-cal and added this line in my JavaScript file: import VueCal from 'vue-cal' I encountered an error message in the console saying: Failed to resolve module specifier "vue-cal" ...