Vue3 TypeScript may potentially have an object that is 'undefined'

This piece of code is Vue3 with TypeScript-based.

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

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

When compiling the code in production, an error occurs on the following line:

this.tenants = payload;

The error indicates that the object is possibly 'undefined'.

How can I resolve this issue?

Answer №1

It is important to note that arrow functions do not work for defining actions because they depend on the this keyword.

Instead, consider using the following approach:

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

Answer №2

While @alexwbt provided insight into the issue and solution, an additional approach could involve specifying Setup Stores instead of using 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,
  };
});

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

Javascript/jquery functions perfectly in all browsers except Firefox

This particular piece of code seems to be functioning properly in Internet Explorer 8, Chrome, and Safari, however, it is not working as expected in Firefox: <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></scr ...

Contrasting `Function` with `(...args: any[]) => any`

Can you explain the difference between Function and (...args: any[]) => any? I recently discovered that Function cannot be assigned to (...args: any[]) => any. Why is that so puzzling? declare let foo: Function; declare let bar: (...args: an ...

Navigating through embedded arrays in Angular

JSON Object const users = [{ "name":"Mark", "age":30, "isActive" : true, "cars":{ Owned : ["Ford", "BMW", "Fiat"], Rented : ["Ford", "BMW", "Fiat" ...

Creating dynamic keys to insert objects

In my coding project, I am dealing with an empty array, a value, and an object. Since there are multiple objects involved, I want to organize them into categories. Here is an example of what I envision: ARRAY KEY OBJECT OBJECT KEY OBJECT ...

What is the best way to access event.target as an object in Angular 2?

Apologies for my limited English proficiency. . I am trying to write code that will call myFunction() when the user clicks anywhere except on an element with the class .do-not-click-here. Here is the code I have written: document.addEventListener(' ...

Revise and optimize the solution for an algorithm using JavaScript

I recently participated in a technical interview for a software development company. The question presented to me was as follows: Given an array of numbers (n), find two numbers that sum up to a target number (k) and display them. Example: Inpu ...

Troubleshooting the failure of the fetch function in my React application

Currently, I am delving into full-stack development with a focus on Js, React, and Express coupled with a Postgres database. The server is configured to run on localhost:5003, and the backend app.js file contains the following code: const express = require ...

Ensuring the proper typescript type for assigning a value in react-hook-form

I'm encountering an issue when trying to pass the function setValue() down to a child component. The error message I receive is: Type 'UseFormSetValue<Inputs>' is not assignable to type 'UseFormSetValue<Record<string, any> ...

Guide to importing multiple controllers using express

For my upcoming full stack project, I am working on various controllers like signup, login, and profile. Instead of manually requiring each controller and adding them to the app using individual lines of code, I am seeking a more efficient solution. I env ...

The error message for ExpressJS states: "Headers cannot be set after they have already been sent."

Currently, I'm facing a challenge with ExpressJS and am having trouble finding the necessary documentation to resolve it. Technology Stack: body-parser: 1.17.0 express 4.15.0 multer: 1.3.0 MongoDB Postman The current view consists of 3 fields: n ...

When consecutive DOM elements are hidden, a message saying "Hiding N elements" will be displayed

Provided a set of elements (number unknown) where some elements should remain hidden: <div id="root"> <div> 1</div> <div class="hide"> 2</div> <div class="hide"> 3</div> <div class="hide"&g ...

Using a conditional statement to wrap a react Route

Currently, I am facing a challenge while working with react router. Initially, I had two distinct components being rendered under the same route - one with a parameter and one without (this was how the routes were distinguished). Now, my goal is to add opt ...

Customizing the Zoom Control Style in Vue Leaflet

I'm currently working on developing a Map App in Dark Mode using Vue, but I've encountered an issue with changing the style of the Zoom Control. Here's what I have tried so far: template> <div class="main-map"> <l ...

Displaying the data from a database on a browser using node.js, MySQL, and Jade

Currently, I am delving into Node.js, Express.js, and Jade while utilizing a MySQL database. As a newcomer to node.js, I decided to start with something simple: presenting data from the database in a table on the browser. Unfortunately, my attempts have no ...

How to Eliminate Image Flickering While Loading in a React Component

Currently, I am developing a React component that takes an imageUrl and displays it on a canvas with a deliberate 2-second delay to mimic loading time for larger images. However, I have encountered a problem: when the imageUrl changes in the parent compone ...

Error: You can't use the 'await' keyword in this context

I encountered a strange issue while using a CLI that reads the capacitor.config.ts file. Every time the CLI reads the file, it throws a "ReferenceError: await is not defined" error. Interestingly, I faced a similar error with Vite in the past but cannot ...

Error message "TypeError: onClick is not a function" occurs when attempting to use a prop in a functional component

I am encountering issues while trying to utilize the onclick function as props. It shows an error message 'TypeError: onClick is not a function' when I click. What should I do? 7 | <Card 8 | onClick={() => onClick(dish ...

Tips for successfully sending an array of numbers using TypeScript and React

Exploring Types in React is new to me and I'm still navigating my way through it. My current challenge involves adding numbers from a form within a child component to an existing array of numbers. To tackle this, I've initialized a useState hoo ...

Transform a PNG image with transparency into a JPEG file using imagemagick

Consider utilizing the imagemagick npm module for your image manipulation needs. In the task of converting a .png file with a transparent background to a .jpeg with a white background, you may encounter challenges. Here is an example: const ImageMagick ...

Even though I included a key prop for each item, I am still encountering the error message stating that every child in a list should have a distinct "key" prop

I have been trying to retrieve data from a rest API and display it as text on my browser. However, I am encountering the following error: index.js:1 Warning: Each child in a list should have a unique "key" prop. Below is how I have set up the key prop. ...