[Nuxt.js/Typescript] Accessing Vuex data in Nuxt.js using Typescript

Hello, I am new to Typescript and I have encountered an issue with setting Objective Data to Vuex store.

Here is the Objective data of Users (also known as account).

# models/User.ts

export interface IUser {
  email: string | null
  name: string | null
}

export class UserClass implements IUser {
  email: string | null
  name: string | null

  constructor(email: string | null, name: string | null) {
    this.email = email
    this.name = name
  }
}
# store/accounts.ts

import { UserClass } from '~/models/User'

@Module({ stateFactory: true, namespaced: true, name: 'account'})
export default class Account extends VuexModule {
  user: UserClass | null = null

  get currentUser() {
    return this.user
  }

  @Mutation
  storeUser(user: UserClass | null){
    this.user = user
  }

  @Action({})
  setUser(user: UserClass | null){
    this.storeUser(user)
  }
}
# utils/store-accessor.ts

import { Store } from 'vuex'
import { getModule } from 'vuex-module-decorators'
import Account from '~/store/account'

let accountStore: Account

function initializeStore(store: Store<any>): void {
  accountStore = getModule(Account, store))
}
export { initializeStore, accountStore }
# components/Sample.vue

<template>
  <div>
    <p>NAME: {{currentUser.email}}</p>    // ★error !
  </div>
</template>
export default class SampleCmp extends Vue {
  @Prop() currentUser: UserClass | null = accountStore.currentUser
}

I am trying to access the email using currentUser.email, but I keep getting an error

Cannot read property 'email' of null
. If I only use currentUser, the stored data such as
{email: [email protected], name: dummy}
is displayed on the page as it is.

Can someone please advise on what steps I should take to resolve this issue? Your help would be much appreciated!

Thank you in advance.

Answer №1

If you're looking to enhance your component with Vuex functionality, consider using the vuex-class library that comes pre-installed with nuxt-property-decorator.

As you declare your component, make sure to import the namespace from nuxt-property-decorator as well:

import { Vue, Component, namespace } from 'nuxt-property-decorator'
const user = namespace('user')

This will enable you to easily access your user store properties by utilizing vuex-class decorators:

@user.Getter
public currentUser!: string


@user.Mutation
public storeUser!: (data: UserClass | null) => void

@user.Action
public setUser(user: UserClass | null) => void

To dive deeper into this topic, check out the vuex section of this article.

Alternatively, for more guidance on integrating TypeScript with Nuxt, the official documentation recommends exploring the nuxt-typed-vuex package.

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

What is the reason for the return of undefined with getElementsByClassName() in puppeteer?

Currently, I am utilizing puppeteer to fetch certain elements from a webpage, specifically class items (divs). Although I understand that getElementsByClassName returns a list that needs to be looped through, the function always returns undefined for me, e ...

Error encountered in Angular 2 with RXJS Observable: Unable to call function catch() on this.http.get(...).map(...) due to TypeError

Everything was running smoothly with my Service until today, when I encountered the following error: TypeError: this.http.get(...).map(...).catch is not a function. Upon debugging the code, it crashes at the catch method. import { Test } from "./home.c ...

Jasmine-ts is encountering a problem related to a subpath within a package, causing

Embarking on a journey of jasmine unit testing, I am encountering challenges when trying to run jasmine and locate my TypeScript written specs. Using jasmine-ts, I typically execute the following command: jasmine-ts --config=spec/support/jasmine.json The ...

Utilizing multiple page objects within a single method in Cypress JS

I have been grappling with the concept of utilizing multiple page objects within a single method. I haven't been able to come up with a suitable approach for implementing this logic. For instance, consider the following methods in my page object named ...

Enhancing the Value of BehaviorSubject with Object Assign in Angular using Typescript and RxJs

I have a user object stored as a BehaviorSubject which is being observed. I need help figuring out how to detect if a specific value within my user object has changed. I've noticed that my current implementation doesn't seem to work correctly, a ...

Use JavaScript's Array.filter method to efficiently filter out duplicates without causing any UI slowdown

In a unique case I'm dealing with, certain validation logic needs to occur in the UI for specific business reasons[...]. The array could potentially contain anywhere from several tens to hundreds of thousands of items (1-400K). This frontend operation ...

Using parameters and data type in Typescript

When I remove <IFirst extends {}, ISecond extends {}> from the declaration of this function, the compiler generates an error. Isn't the return value supposed to be the type after the double dot? What does <IFirst extends {}, ISecond extends { ...

Determine the type of sibling parameter

Creating a Graph component with configurations for the x and y axes. The goal is to utilize GraphProps in the following manner: type Stock = { timestamp: string; value: number; company: 'REDHAT' | 'APPLE' | ... ; } const props: ...

What is preventing me from defining the widget as the key (using keyof) to limit the type?

My expectations: In the given scenario, I believe that the C component should have an error. This is because I have set the widget attribute to "Input", which only allows the constrained key "a" of type F. Therefore, setting the value for property "b" sho ...

Discovering the process of reaching service members through an HTML View

Currently, I am in the process of learning Angular 2 and find myself unsure about the most efficient way to update the view. For instance, let's say I have two components: User and Main. The User component retrieves a list of users from the UserServ ...

What is the overlay feature in Material-UI dialogs?

I recently started using the React-Redux Material-UI package found at http://www.material-ui.com/#/components/dialog My goal is to implement a grey overlay that blankets the entire dialog element, complete with a circular loading indicator after the user ...

NextJS and AWS Amplify collaboration for secure authentication routing

After hours of research, I'm struggling to navigate the authentication routing in NextJS combined with AWS Amplify. As a newcomer to NextJS, I want to implement a feature that disables the login/register page for users who are already logged in and pr ...

Hiding columns in TanStack Ver 8: A step-by-step guide

Can someone assist me with dynamically hiding specific columns in Tanstack table ver 8? I have a column defined as follows: { header: "Case Number", accessorKey: "caseNumber", visible: false, // using this value ...

Received an unexpected argument count of 1 instead of the expected 0 while passing a function as a prop to a child component

I transferred the deleteImgfunc function from the insertFarmDiaryDetail component to the InsertFarmDiarySubPage component, which acts as a child component. DeleteImgfunc is a parameter-receiving function. Despite creating an interface and defining paramet ...

In Typescript, issues arise when trying to assign types with inheritance in Generics - Type mismatch detected

As I work on creating a generic parent class to handle multiple children, I have encountered a challenge. My goal is to define an abstract function in the parent class that will take in a child object and return that same class. Here's my initial atte ...

I encountered a problem while integrating antd and moment.js in my React project

I am currently using the antd date-picker in my React project with TypeScript. Encountered an error: Uncaught Type Error: moment is not a function. If anyone has a solution, please assist me. .tsx file:: const dateFormat = 'MM-DD-YYYY'; < ...

tips for sending types as properties in a versatile component

I am facing a challenge with passing types as props to a reusable component. I have a component where I pass rows and headings as props, but I need to find a way to pass types as props as well. Below is the code for my reusable component: import { TableCe ...

The functionality of the String prototype is operational in web browsers, but it encounters issues

Version: 8.1.0 The prototype I am working with is as follows: String.prototype.toSlug = function () { return (<string>this) .trim() .toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w\-]+/g, '') ...

Leveraging the power of Angular 5 to seamlessly integrate two distinct components on

I am exploring a way to render an additional component on the current page instead of navigating to a new one. Here is my setup: <button mat-button color="primary" [routerLink]="['/tripspath', trip.tripId]" style="cursor: pointer">View Rou ...

Is there a workaround for the React useContext issue in Typescript aside from using <Partial>?

I am currently working on a React app that utilizes the useContext hook, but I am facing challenges with correctly typing my context. Here is the code snippet in question: import React, { useState, createContext } from 'react'; import endpoints f ...