Tips for accessing and manipulating an array that is defined within a Pinia store

I have set up a store to utilize the User resource, which includes an array of roles. My goal is to search for a specific role within this array. I've attempted to use Array functions, but they are not compatible with PropType<T[]>.

import router from "@/router";
import axios from 'axios';
import { defineStore } from "pinia";
import { PropType } from "vue";
import { ApplicationConstants } from '../utils/Constants';

type Role = {
    name: string;
}

export const useUserStore = defineStore('user', {
    state: () => ({
        currentUserId: Number,
        currentUserUsername: String,
        currentUserRoles: Array as PropType<Role[]>,
        isLoggedIn: false
    }),
    getters: {
        getCurrentUserId: (state) => state.currentUserId,
        getCurrentUsername: (state) => state.currentUserUsername,
        getCurrentUserRoles: (state) => state.currentUserRoles,
        isUserLoggedIn: (state) => state.isLoggedIn,
        // hasCurrentUserRole: (state) => { return (role: String | Role) ????}
    },
    actions: {
        logIn(username: string, password: string) {
            const authDTO = {
                "username" : username,
                "password" : password
                }
                const loginResponse = axios({
                    method: 'post',
                    url: ApplicationConstants.API_LOGIN_URL,
                    data: authDTO
                }).then((loginResponse) => {
                    /** Set JWT access token in LocalStorage. */
                    const token = loginResponse.headers["access-token"];
                    localStorage.setItem("accessToken", token);
                    /** Set current user credentials. */
                    this.currentUserId = loginResponse.data.id;
                    this.currentUserUsername = loginResponse.data.username;
                    this.currentUserRoles = loginResponse.data.roles;
                    this.isLoggedIn = true;
                    /** Go to Home page. */
                    console.log("inside login in userstore");
                    router.push("/");
                }).catch((error) => {
                    
                });
        },
        logOut() {
            this.$reset();
            this.isLoggedIn = false;
            router.push("/login");
        },
        containsRole(roleName: String | Role)  {
            // how??
        }
    }
});

I am utilizing Vue3 alongside Composition API and TypeScript.

Answer №1

When you return an object, make sure your values have types instead of actual values. One approach is to set default values like this:

state: () => ({
    currentUserId: 0,
    currentUserUsername: "",
    currentUserRoles: [] as Role[],
    isLoggedIn: false
}),

Alternatively, you can define an interface with null default values:

state: (): StoreStateI => ({
    currentUserId: null,
    currentUserUsername: null,
    currentUserRoles: [],
    isLoggedIn: false
}),

interface StoreStateI {
   currentUserId: null | number
   currentUserUsername: null | string
   currentUserRoles: Role[]
   isLoggedIn: boolean
}

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

The function 'ShouldWorkController' was expected but is not defined, receiving undefined instead

Whenever I attempt to connect a controller to a template using the angular-ui-router $stateProvider, I encounter this error message: 'ShouldWorkController' is not a function. Got undefined. Surprisingly, when I define the controller within the ...

Mastering Typescript lookup types - effectively limit the properties included in a merge operation with the Partial type

Exploring lookup types, I'm interested in creating a safe-merge utility function that can update an entity of type T with a subset of keys from another object. The objective is to leverage the TypeScript compiler to catch any misspelled properties or ...

What is the best way to segregate Express routes from server.js?

I've been closely following a Vue SSR guide on GitHub and noticed that the author has organized their Express routes within a file named server.js. For better organization, I prefer to keep my Express routes in a file called router.express.js located ...

The integration between Vue and Laravel for sending emails is experiencing technical glitches and is currently not functioning as expected

Hello, I'm facing an issue and need your assistance. Despite trying various solutions, nothing seems to work for me, and I can't figure out why. Here is the snippet of my Vue app.js: import './bootstrap'; import { createApp } from &ap ...

What is the best way to depict object key replacements within a Typescript definition?

I currently have these types: type PossibleKeys = number | string | symbol; type ValueOf<T extends object> = T[keyof T]; type ReplaceKeys<T extends Record<PossibleKeys, any>, U extends Partial<Record<keyof T, PossibleKeys>> = ...

Leverage videojs-vr within a Vue.js component

I have been experimenting with integrating the videojs-vr package, which I installed through npm, into a Vue.js component. However, I encountered an error: TypeError: videojs is not a function at VueComponent.mounted (VR.vue?d2da:23) at callHook (vue.esm. ...

Tips on utilizing index and eliminating React Warning: Ensure every child within a list has a distinct "key" prop

Hello, I am encountering an issue where I need to properly pass the index in this component. Can you help me figure out how to do that? Error: react-jsx-dev-runtime.development.js:117 Warning: Each child in a list should have a unique "key" prop ...

Angular2 - Actively selecting a checkbox in an ngFor loop with a reactive form

There is an object retrieved from a database that consists of a list of names with their corresponding IDs, as well as a flag to indicate whether they are selected or not. Object: let items = [{ ID: 1, Name: 'Item A', Selected: 'Y ...

Angular 2 child route causing application to become unresponsive

Hey there, I'm currently working on setting up child routes for my Angular app and this is what I have so far: import {bootstrap} from 'angular2/platform/browser' import {CommercifyComponent} from './commercify.component' import { ...

Passing data from ModalService to a component

Currently, I am attempting to utilize the ngx-bootstrap-modal in order to transfer data from a modal service to a modal component. While reviewing the examples, it is suggested to use the following code: this.modalService.show(ModalContentComponent, {init ...

The data type 'A | B' cannot be assigned to type 'A & B'

What could be causing the compilation error in this code? type A = { n: number } type B = { s: string } type Thing = { a: A b: B } function update(obj: Thing, path: keyof Thing) { obj[path] = obj[path] } It seems like both sides of the assignment sh ...

Ways to confirm non-null values and bypass the row if it is

I have been attempting to compare 2 dates in order to appropriately display data in a table. I have tried the following approach: ${this.dateToCompare.getTime()} > ${row.CreateDate.getTime()} However, there is an issue where CreateDate has a null value ...

Displaying error messages in Angular Material upon clicking a button

I am struggling with validation using the <mat-form-field> and <mat-error>. The validation works as expected when the user tabs out of the input without filling it. However, I'm facing a challenge in making this error show up when a button ...

What is the process for generating an index.d.ts file within a yarn package?

I'm facing an issue with creating the index.d.ts file for my yarn package. Here is my configuration in tsconfig.json: { "include": ["src/**/*"], "exclude": ["node_modules", "**/*.spec.ts"], " ...

Exploring the Issue with SWR Hook in Next.js using TypeScript

Seeking assistance with the SWR hook as I navigate through some challenges while attempting to use it effectively. This time, the issue appears to be minor. The objective is to set a breakpoint in my API to retrieve data, using axios. The problem arises ...

Should the request be sent to the parent or child component?

When a page is divided into various components, the data for each component is fetched asynchronously. Therefore, the parent component should trigger the request and pass it on to the child component, or alternatively, the request can be directly sent to ...

receiving a response within an HTML tag using Vue.js

Could someone assist me with retrieving data in an HTML tag similar to how I can do it with console.log? I am trying to get the value console.log(this.likeDes[0].like_dislike) to display within a <span class="fa fa-heart-o"></span> ...

Vue Google Tag Manager Error: This file type requires a specific loader to be handled correctly

I have integrated "@gtm-support/vue2-gtm": "^1.0.0" in one of my Vue-2 applications, with Vue versions as below: "vue": "^2.5.2", "vue-cookies": "^1.5.4", "vue-i18n": "^8.0.0", "vue-recaptcha": "^1.1.1", "vue-router": "^3.0.1", "vue-scrollto": "^2.17.1", " ...

Typescript is throwing an error with code TS2571, indicating that the object is of type 'unknown'

Hey there, I'm reaching out for assistance in resolving a specific error that has cropped up. try{ } catch { let errMsg; if (error.code === 11000) { errMsg = Object.keys(error.keyValue)[0] + "Already exists"; } return res.status ...

Can you provide a guide on setting up and utilizing mathlive within NuxtJS?

Can anyone assist me? I am trying to figure out why my code is not working or if I have implemented it incorrectly. I used npm i mathlive to obtain input. However, following the instructions for implementing nuxt plugins in the documentation has not yield ...