The Pinia getter appears to be stuck on an old value and is

Using Vue with Pinia has been a great experience for me. Here's what my store structure looks like:

interface LoginStore {
  token?: string;
}

export const useLoginStore = defineStore('login', {
  state: () => ({} as LoginStore),
  actions: {
    async login(email: string, password: string): Promise<boolean> {
      try {
        const result = await api.post('/api/user/login', { email, password });
        this.token = result.data.data.token;
        return true;
      } catch (err) {
        console.error('Login Error', err);
        return false;
      }
    },
  },
  getters: {
    isLoggedIn: (state) => {
      return state.token != null;
    }
  }
});

Even though the login() function successfully logs in the user, the isLoggedIn getter still returns false.

I've double-checked and I am using storeToRefs correctly to access the store (referenced issue).

const { isLoggedIn } = storeToRefs(useLoginStore());

I'm puzzled by why isLoggedIn remains false despite state.token being assigned a value. Any thoughts on this?

Answer №1

It may seem strange, but properties of type undefined must be included in the initial state of the store for it to function correctly. If you omit them during initialization:

state: () => ({} as LoginStore),

The getter will not work as expected. However, if you explicitly initialize them with undefined, the getter will function properly.

state: () => ({
  token: undefined,
} as LoginStore),

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

I am eager to design a form input field within the vuetify framework

https://i.sstatic.net/zbCfI.png I'm having trouble creating a text field in Vuetify where the button and height are not behaving as expected. I've attempted to adjust the height multiple times without success. Although I have the necessary CSS, ...

Using Angular 2+ to make HTTP POST requests and interact with the GDrive API. Implementing resumable file uploads

I am currently facing a challenge with uploading files to Google Drive using Angular 2. I have managed to upload files successfully, but they end up being labeled as "Untitled" without any title. Below is the code snippet I am using for the upload process ...

Create a custom class that functions similarly to a dictionary

Is it not feasible to achieve this? interface IMap { [key: string]: string; } class Map implements IMap { public foo = "baz"; } But instead of success, I encounter the error: TS2420:Class 'Map' does not correctly implement 'IMap& ...

Improving the method to change a string into a string literal in TypeScript

Utilizing a third-party tool that has specified editorStylingMode?: 'outlined' | 'underlined' | 'filled'; I have set the value in my environment.ts file (in Angular) as shown below export const environment = { productio ...

Exploring the vast world of deep type information in the Typescript JSON

Examine the contents of the file data.json: { "au": { "name": "Australia", "market_id": "111172", "language_code": "en_AU" }, "br": { "nam ...

Creating nested routes with parameters in NestJS is a powerful feature that allows for dynamic routing

I have a requirement to create an API with routes that share a common URL part along with a parameter. For my particular case, the routes should follow this structure: /accounts/:account/resource1/:someParam /accounts/:account/resource2/:someParam/whate ...

Is there a method to enable autoplay for videos with sound in Chrome while using Angular?

Currently, I am developing a spa where I need to display a banner video at the top of the website. Is there a way to automatically unmute the audio when the video is loading initially? I have attempted to unmute the video and override it, but unfortunatel ...

Setting a variable in a v-tab using Vuetify now only takes 2 easy clicks!

I'm currently utilizing Vuetify and vuejs to develop a tab system with 3 tabs. The tabs are being switched dynamically by binding to the href of a v-tab. Each time I click on a tab, the value of the speed variable is modified. However, I'm encoun ...

Tips for keeping a button selected in each row of a table

I'm confused about a simple issue. I have a table that fetches data from a JSON file, where each row represents a JSON field. In each row, I added two buttons (Like/Dislike) to assess the search quality. However, whenever I click on the like button on ...

Pass information from the child component to the parent component using Vue.js

I am currently working on a modal component named modal_form.vue, which I am using inside another component called index.vue. My goal is to pass a data variable from modal_form.vue to index.vue. Can anyone provide me with an example of how to achieve this ...

Tips for choosing a specific quantity and adjusting its value

Just starting out with Ionic 3 and looking for some help with the code. Can anyone assist me in understanding how to change the value of an item in a shopping cart and have the subtotal reflect that change? cart.ts private _values1 = [" 1 ", "2", " 3 "," ...

Display different images based on user selection in vue.js

I am new to working with vue.js and I'm facing a challenge. My goal is to display images of NBA players based on the selected criteria using vue.js. For instance, if the Dunk contest champion is chosen, only images of Kobe and Jordan should be display ...

I'm curious if someone can provide an explanation for `<->` in TypeScript

Just getting started with TypeScript. Can someone explain the meaning of this symbol <->? And, is ProductList actually a function in the code below? export const ProductList: React.FC<-> = ({ displayLoader, hasNextPage, notFound, on ...

How to efficiently iterate through an array in Nuxt using a v-for directive and effectively display the data

I am struggling with looping through nested data from a JSON file on my e-commerce website. Despite trying several methods, I have not been successful in achieving this. async fetch() { this.post = await fetch( `http://test.com/api.php?id=${this. ...

Is it advisable to relocate TypeScript declarations to their own file?

My code file is getting too long with both declarations and other code mixed together. Below is a snippet from my ./src/index.ts file: // --> I want to move this to a separate file export interface Client extends Options { transactionsCounter: num ...

angular 6's distinctUntilChanged() function is not producing the desired results

I have a function that retrieves an observable like so: constructor(private _http: HttpClient) {} getUsers(location){ return this._http.get(`https://someurl?location=${location}`) .pipe( map((response: any) => response), ...

Declaring a sophisticated array as a property within another property in Typescript

As a newcomer to Angular and Typescript, I am facing a challenge while declaring a property with a complex array as one of its values. Here is what I have attempted: groupedItem: { customGroupId: string, cgName: string, category: [{ cu ...

Utilize the parameter definition of a function type

Is it possible to reuse parameter types in typescript in the following manner: interface Box { create: (paramToReuse: (value: any) => void) => void } // Can paramToReuse be referenced as a type? For example: let x: Box['create']['p ...

Utilize key-value pairs to reference variables when importing as a namespace

Is it feasible to utilize a string for performing a lookup on an imported namespace, or am I approaching this the wrong way? Consider a file named my_file.ts with contents similar to: export const MyThing: CustomType = { propertyOne: "name", ...

Retrieve the object filtered by a specific group from an array of data

I have a data object that contains various groups and rules within each group item. My task is to filter the rules based on a search query, while also displaying the group name associated with the filtered rule. { "id": "rulesCompany", "group": [ ...