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

Is Typescript capable of identifying void functions automatically?

Being new to Typescript and programming in general. Instead of using: function greet(greeting: string): void; Can I simplify it like this? Is there any type inference? function greet(greeting: string); ...

Error occurs in Typescript when attempting to store data in a record using a pointer

When working with nodes and organizing them into a tree structure, I encounter an issue: This is the definition of the interface: interface IDataObj { children: IDataObj[], frontmatter : { type: string, title: string, path: string}, name: str ...

What is the significance of the colon before the params list in Typescript?

Consider the following code snippet: import React, { FC } from "react"; type GreetingProps = { name: string; } const Greeting:FC<GreetingProps> = ({ name }) => { // name is string! return <h1>Hello {name}</h1> }; Wha ...

Tips for centering a flexbox on a webpage:

<template> <div> <div class="flex justify-center w-full"> <div class="h-px-500 md:w-1/6 bg-orange-200 text-center">1</div> <div class="h-px-500 md:w-1/6 bg-orange-300 text-center">2</div> <div clas ...

What is the best way to organize components in Vue.js?

Currently, I am facing a situation in my Vue router where most of the routes are structured like this: { path: '/somepath', name: 'SomeName', components:{ componentA: componentA, componentB: com ...

Invalid file name detected during the download process

Below is the Javascript code I currently use to download a pdf: var link = document.createElement('a'); link.innerHTML = 'Download PDF file'; link.download = "Report.pdf"; link.href = 'data:application/octet-stream;base64 ...

Display the Vue 3 Component within a mounted div and transfer PHP data

I've taken on a new project that involves integrating Vue 3 into a complex Symfony/Drupal project. Since the project already has a significant amount of PHP code, I'd prefer not to refactor too extensively at this stage. My initial attempt invol ...

What methods can be used in VueJS to restrict users from entering numeric values?

I am struggling to create a validation that prevents users from inputting numeric values into a textbox. I have tried using a native JavaScript solution, but it does not seem to be working on my end. In my textbox, I have set up this trigger v-on:keyup=" ...

Can Vue.js 3 composition be leveraged with v-for to incorporate a query string into a router-link?

I have successfully implemented v-for for a URL path. Now, I am looking to merge the URL path with the query string in the router link tag. The query string will be the date from each item rendered by v-for. Is there a way to dynamically pass this query ...

Can you explain the distinctions between Vue JS and React JS?

As I delve into learning Vue Js and React Js, my search for a detailed comparison between the two on Google left me unsatisfied. I came across resources answering the singular questions "What is Vue js?" and "What is React Js," but none that directly comp ...

Having Trouble with Typescript Modules? Module Not Found Error Arising Due to Source Location Mismatch?

I have recently developed and released a Typescript package, serving as an SDK for my API. This was a new endeavor for me, and I heavily relied on third-party tools to assist in this process. However, upon installation from NPM, the package does not functi ...

PrimeNG Component Containing a Dynamic Dialog Instance

I am experiencing an issue with handling dynamic dialogs in PrimeNG. Is there a solution for managing actions on a dialog other than just using the close option? For instance, in the context of the Kendo-UI dialog example, I can specify the content.insta ...

Working with arrow functions in TypeScript syntax

I came across the following code snippet in TypeScript: (() => { const abc = 'blabla'; ... })(); Can someone explain what exactly this syntax means? I understand arrow functions in JS, so I get this: () => { const abc = &apos ...

Utilize ES6 lodash to map the keys of an object fetched from an API

Currently, I am utilizing Vue 3 to send POST data to my API. The structure of the objects is as follows: const externalResults: ref(null) const resource = ref({ id: null, name: null, state: {} }) Prior to sending the data to the API, I am modifying ...

Using TypeScript to import a Vue 2 component into a Vue 3 application

Recently, I embarked on a new project with Vue CLI and Vite, utilizing Vue version 3.3.4 alongside TypeScript. In the process, I attempted to incorporate the vue-concise-slider into one of my components. You can find it here: https://github.com/warpcgd/vu ...

Solving CORS policy error in a MEAN stack application deployed on Heroku

I've been grappling with a CORS policy error in my MEAN stack app for quite some time now. The specific error message I keep encountering is: "Access to XMLHTTPRequest at <my heroku app url.com/login> from origin has been blocked by CORS ...

Visualizing Dynamic Path on VueJS Using Polygon Map

I am facing some issues with implementing Google Maps in Vue.js. I have created a polygon component as shown below: <script> export default { name: "MapPolygon", props: { google: { type: Object, ...

How to extract key-value pairs from an object in a TypeScript API request

I am trying to extract the data '"Cursed Body": "100.000%"' from this API response using TypeScript in order to display it on an HTML page. Can anyone help me figure out how to do this? API Response { "tier": &q ...

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> ...

Django and Vue: Unable to locate static file

Whenever I am using Django+Vue to develop a web application, I always encounter issues where the static files are not found even though I have placed all the files correctly. The server logs show messages like: WARNING Not Found: /static/js/app.4c2224dc.j ...