Using pinia always results in undefined arrays within the state

Pinia has been a crucial part of my Vue3 projects, and I've encountered a dilemma while trying to store temporary data in Pinia. Here's a snippet from my store file:

// template.ts
export const useTemplateStore = defineStore('template', {
  state: () => {
    return {
      templates: [] as Template[],
      temporary: {
        id: generateUUID(),
        itemList: []
      } as Template
    }
  },
  actions: {
    reset() {
      this.temporary = {
        id: generateUUID(),
        itemList: []
      }
    },
    addItem(item: TemplateItem) {
      this.temporary.itemList.push(item);
    }
  }
})

However, when attempting to add an item to temporary.itemList in my Vue file, it didn't work as expected:

<script setup lang="ts">
// ...
const useTemplate = useTemplateStore();
// both of them failed
useTemplate.addItem({ ... });
useTemplate.temporary.itemList.push({ ... });
</script>

Upon checking the console, the following error messages were displayed: directly push using addItem method

After logging out itemList (

console.log(useTemplate.temporary.itemList)
), it returned as undefined.

I'm puzzled by this issue and would greatly appreciate any assistance or insights offered.

Just for your information, my projects are coded using TypeScript.

Answer №1

This issue might have been triggered by TypeScript.

The JavaScript version seems to be functioning correctly.

const { createApp } = Vue
const { createPinia, defineStore } = Pinia

const useTemplateStore = defineStore('template', {
  state: () => {
    return {
      templates: [],
      temporary: {
        itemList: []
      } 
    }
  },
  actions: {
    reset() {
      this.temporary = {
        itemList: []
      }
    },
    addItem(item) {
      this.temporary.itemList.push(item);
    }
  }
})

const App = {
  setup() {
    const useTemplate = useTemplateStore();
    // both of them failed
    useTemplate.addItem({ item: 1 });
    const addItem2 = () => { 
      useTemplate.temporary.itemList.push({ item: useTemplate.temporary.itemList.length + 1}) 
    }
    return {
      useTemplate,
      addItem2
    }
  }
}

const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.mount('#app')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
<div id="app" v-cloak>
  useTemplate.temporary.itemList: {{ useTemplate.temporary.itemList }}<br/>
  <button @click="addItem2()">Add Item</button>&nbsp;
  <button @click="useTemplate.reset()">Reset</button>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7d1d2c28ac3c2cacee797899694899696">[email protected]</a>/lib/index.iife.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b0b1215121a3b49554b55484b">[email protected]</a>/dist/pinia.iife.js"></script>

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

What is the best way to create an overload signature for a function that could potentially receive either 1 or 2 arguments when called?

Trying to define the signature for a function that can be called with either 1 or 2 arguments, encountering an error stating that the type of the function with 2 arguments is not compatible with the defined type. The specified type: type Response = { st ...

How to send props from a Vue.js component tag in an HTML file

I'm facing an issue with passing props from the HTML to the JavaScript code and then down to a Vue component. Here's a snippet of my index.html file: <div id="js-group-discounts"> <div class="form-group required"> <datepick ...

Locating elements with the same class for links by their href attribute using Protractor and Typescript

I am facing an issue with my HTML code where all the class names are similar, but only the href links are different. What would be the most effective method to locate these links using CSS? I attempted the following approach: test = element.all(by.css(&a ...

Websocket onmessage event triggered just one time

I have implemented a basic WebSocket client in an Angular 6 application. Everything seems to be working fine, except for the fact that both socket.onmessage and socket.addEventListener('message' are only triggered once. There are no errors in th ...

What is the best way to retrieve a function's response depending on the parameters provided?

I am trying to figure out how to determine the data types of copied array elements in my code. let inputArray = [ { test: 1, }, { test: 2, }, ]; function clone(array: any[]): any[] { return Array.from(inputArray); } ...

Verify if the date chosen falls on the current date or any upcoming date within vuejs validation

I am working on a Vue.js component that includes a form where the user needs to select a start date from a date picker. The user should only be able to choose a date that is either today's date or a future date. <div class="w-1/2 mr-2"&g ...

Learn the process of retrieving a file from server.js and showcasing it on an HTML page

I am currently developing a YouTube video downloader using express, HTML, and JavaScript, with plans to transition to Vue.js in the future. Here is a snippet of my code: Index.html <!DOCTYPE html> <html lang="en"> <head> & ...

Error happens while running the setInterval loop in the code execution

I encountered a peculiar issue while developing a 2D game in Angular. The function in my component calls an async function to load the sprites, then executes the game loop in the callback GameComponent.ts: constructor(private loader: AppService, privat ...

Guide on incorporating Firebase "onSnapshot" listener values to update a Vue "ref" variable

I have implemented a Vue composable feature that utilizes a Firebase onSnapshot listener to track data changes. The goal is to update a ref called documentsArray whenever there is a change detected by the listener. Interestingly, when I log the contents ...

How to Alphabetize an Array of Strings Containing Numbers using TypeScript and Angular

I'm working with an array that looks like this: arr = ["100 abc", "ad", "5 star", "orange"]; The goal is to first sort the strings without numbers at the beginning, then sort the strings with numbers added at t ...

Building on the powerful foundation of Laravel 5.3, we have crafted a seamless Vue 2.0 form for

I'm encountering difficulties with user authentication using Vue 2.0. Within my Vue application, I have a form where users input their information and submit it via POST to a Laravel endpoint. Once the user is created in the UserController method wi ...

Display the total number of selected items when using Vuetifyjs v-autocomplete with multiple selection

I am utilizing the Vuetifyjs/v-autocomplete component with the "multiple" props enabled. By default, the component shows all selected items on the input field. Is there a way to customize the display of the selected items to only show the total number of s ...

Removing an image from the files array in Angular 4: A step-by-step guide

I have recently started working with typescript and I am facing a challenge. I need to remove a specific image from the selected image files array before sending it to an API. app.component.html <div class="row"> <div class="col-sm-4" *ngFor ...

When using Vue with CSS3, placing an absolute positioned element within a relative wrapper can cause issues with maintaining the

Just starting out with Vue and diving into the world of CSS3! I'm currently working on a component that you can check out here: https://codesandbox.io/s/yjp674ppxj In essence, I have a ul element with relative positioning, followed by a series of di ...

Using styled-components to enhance an existing component by adding a new prop for customization of styles

I am currently using styled-components to customize the styling of an existing component, specifically ToggleButton from material ui. However, I want my new component to include an additional property (hasMargin) that will control the style: import {Toggle ...

When using Reactjs, it is not possible to update the state using useState within the handleSubmit function

I've encountered a puzzling error and could use some assistance in understanding it better. After calling setServerList(data.data), the data still appears empty when I attempt to use it. export const KernelUpdateSearch = (props: RouteComponentProps) ...

Changing the Row's Background Color in Angular When the Button is Clicked

My code includes a list where each row has a button to open a sidebar. Due to the large number of elements in the list, I want the background color of the row to turn yellow when the button is clicked, as a way to indicate what has been selected. Currently ...

Retrieve predefined values from a TypeScript controller in Stimulus using the default Symfony configurations

Currently, I am delving into the realm of Stimulus using a standard Symfony6 and Encore setup, with the only notable difference being my use of Typescript. As per the guidance in the Stimulus documentation, typed values should be utilized in the following ...

Angular: ngModelChange not updating value in dropdown menu

I have successfully implemented a dropdown feature like this: <select (ngModelChange)="onChange($event)"> <option *ngFor="let quantity of quantities" [ngValue]="quantity"> {{ quantity }} ...

Can anyone guide me on incorporating FontAwesome into my Vue/Express/hypernova-vue application?

I am currently developing a Rails app that utilizes hypernova-vue to integrate Vue3 micro frontend apps/components across the site. I have created a small npm library containing components that are used by the Vue component micro frontends. However, after ...