skip to Main Content

The code below is based on vue3 with typescript used.

export interface TenantDto {
  uuid: string;
  name: string;
}

export const useTenantStore = defineStore('tenant', {
  state: () => ({
    tenants: [],
  }),
  actions: {
    setMyTenants: (payload: TenantDto[]) => {
      this.tenants = payload;
    },
  }
);

compiling the code in production produces a error on the line

this.tenants = payload;

The error is saying Object is possibly ‘undefined’.

how would I get it around ?

2

Answers


  1. You cannot use arrow function to define actions since it relies on the this keyword.

    Try this instead:

    export const useTenantStore = defineStore('tenant', {
      state: () => ({
        tenants: [],
      }),
      actions: {
        setMyTenants(payload: TenantDto[]) {
          this.tenants = payload;
        }
      }
    });
    
    Login or Signup to reply.
  2. However @alexwbt described the problem & solution, another alternative could be to specify Setup Stores instead of Option Stores.

    import { defineStore } from 'pinia';
    import { ref } from 'vue';
    
    export const useTenantStore = defineStore('tenant', () => {
      const tenants = ref([]);
      
      const setMyTenants = (payload) => {
        tenants.value = payload;
      }
    
      return {
        tenants,
        setMyTenants,
      };
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search