Pinia not properly updating state with an array of objects in Vue 3

Currently working with Vue 3 and Pinia, I have a store called cards.js structured like this:

import { defineStore } from 'pinia'
import { useLanguageStore } from './language'
import axios from 'axios'


export const useCardsStore = defineStore({
    id: 'cards',
    state: () => ({
        cards: []
    }),
    actions: {
        async generateCards() {
            const languageStore = useLanguageStore();

            this.cards = (await axios({
                method: "post",
                url: "<endpoint>", // sample endpoint
                data: {
                    text: languageStore.sentence,
                    language: languageStore.language
                }
            })).data.map(token => ({
                text: token.text,
                pos: token.pos,
            }));

            console.log(this.cards)  // see (*)
        }
    }
})

Within a component, I implement something similar to this:

<template>
...
   <input v-model="sentence">
   <button @click.prevent="generateCards()">Generate</button>
...
</template>

<script setup>
import { storeToRefs } from 'pinia'
import { useCardsStore } from '../stores/cards'
import { useLanguageStore } from '../stores/language'

const { cards } = storeToRefs(useCardsStore())
const { sentence } = storeToRefs(useLanguageStore())
const { generateCards } = useCardsStore()
</script>

Despite clicking the button and updating this.cards (*), the console output is as follows:

Proxy {0: {…}, 1: {…}, 2: {…}, 3: {…}}
  [[Handler]]: Object
  [[Target]]: Array(4)
    0: {text: 'this', pos: 'PRON'}
    1: {text: 'is', pos: 'VERB'}
    length: 2
  [[Prototype]]: Array(0)
  [[IsRevoked]]: false

(Showing that the array is being generated correctly) However, in Vue devtools and within the application itself, the state of cards remains unchanged.

Any assistance on this matter would be greatly appreciated. Thank you.

Note: I followed a tutorial available here.

Answer №1

The solution was provided by @Phil. Referencing the documentation, it's advised not to destructure the store. Instead of:

const { generateCards } = useCardsStore()

You should do:

const store = useCardsStore()

And then utilize store.generateCards instead of just store in your template.

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 showcase my customized license plate on the following page?

I need help with incorporating my number plate builder into a website. I have utilized JQUERY and JAVASCRIPT for the styling aspect, but now I want to display the designed plate on the next page. Can someone guide me on how to achieve this using PHP, JQUER ...

Displaying a default value in Quill text editor within Vue3

Looking at the image, you can see that I have a text editor with Quill in my admin panel. When I write something in the text editor and want to display it, everything works fine. For instance, if I want to write a description in bold, it appears on the fro ...

Having trouble with the base64 output in React image cropping?

I am having some difficulties cropping and uploading an image to the server. The API server requires the image in base64 format, but I am receiving it as a blob. Does anyone know of a workaround for this issue? Any help would be greatly appreciated! I&apos ...

How can a value be retrieved from an async/await function in Vue?

I have a query regarding an async function embedded in my HTML. The issue I am facing is that it returns a promise instead of the desired value. Can anyone suggest a way to properly display the value obtained from the asynchronous function? <div> ...

Using Ajax for updating table content on a JSP webpage section

I am working on implementing Ajax functionality for a table to enable partial updates every hour. Below is a snippet of my JSP code: < head > < meta http - equiv = "Content-Type" content = "text/html; charset=ISO-8859-1" > < titl ...

Steps to showcase a HTML modal based on the outcome of a JavaScript/AJAX database query

Currently in the process of developing a Facebook game utilizing html and Javascript. With two modals on an html page (referred to as ModalA and ModalB), the goal is to link both modals to a single button, triggering the display of only one modal based on ...

What could be causing this Angular controller to throw the error message "Error: Unknown provider: nProvider <- n"?

Check out the jsFiddle code here: <div ng-app=""> <div ng-controller="FirstCtrl"> <input type="text" ng-model="data.message" /> {{data.message + " world"}} </div> </div> function FirstCtrl($scope) { ...

Angular app sends a JSON request and receives no data in response

It seems like Angular may be loading the page before fully receiving all the information from JSONP. There are times when refreshing the page multiple times eventually displays the information, but it's not consistent. Interestingly, the code used on ...

The button should only be visible when the input is selected, but it should vanish when a different button within the form is

Having an issue with displaying a button when an input field is in focus. The "Cancel" button should appear when a user interacts with a search bar. I initially used addEventListener for input click/focus to achieve this, but ran into a problem: on mobile ...

Unable to retrieve the value from an object (Javascript)

window.addEventListener('keydown', (e) => { let arrowsObj = { "ArrowUp": 1, "ArrowDown": 2, "ArrowLeft": 3, "ArrowRight": 4 } let eventKey = e.key; console.log(arrowsObj.eventKey); }); Despite p ...

Tips for sending JSON-formatted data from a route to jQuery

Currently, I am facing a challenge with passing a JSON file retrieved from an API to jQuery. The goal is to implement an infinite scroll functionality using jQuery before displaying it in an EJS file. The issue arises when `res.json(data)` is utilized; ins ...

Retrieve the PDF document from the AJAX call and save it as a

My goal is to have the browser automatically download a PDF file that is received from an AJAX response. After reading about how to download a PDF file using jQuery AJAX, I attempted to simulate a click/download event in this way: var req = new XMLHt ...

Stylized search input inspired by Pinterest with a bubbly design

When it comes to my search bar, I want the user's entered keywords to be displayed within a bubble that has a delete option when they press space to add another keyword. This functionality is similar to what Pinterest does with their search bar, as de ...

Transitioning create-react-app from JavaScript to Typescript

A few months ago, I began a React project using create-react-app and now I am interested in transitioning the project from JavaScript to TypeScript. I discovered that there is an option to create a React app with TypeScript by using the flag: --scripts-v ...

What is the reasoning behind npm modules such as material-ui exporting both es6 and es5 files?

When installing several npm modules, such as @material-ui/core, I noticed that there are three different ways to import the same React component: import { AppBar } from '@material-ui/core' import AppBar from '@material-ui/core/AppBar/AppBar ...

Experiencing inaccuracies in Magento's item validation process when checking the quantity of items being added to the cart

Upon entering a text string in the quantity field of the "Add to Cart" input box, Magento does not display an error message but instead considers it as a quantity of "1". Is there a way to modify this behavior and have the validation system mark strings ...

Vuetify Event Calendar

Currently, I am using the Vue calendar with Vuetify version 2.1.x. I am trying to retrieve the time from a specific slot when it is clicked like this: @click:time="test" <v-calendar ref="calendar" :locale="$i18n.locale" v-model="schedulerObj.calV ...

Converting a JavaScript object into HTML output

I have received the following JSON data: [    {       "fields": {          "url": "http://www.domain_name.co.uk/MP3/SF560783-01-01-01.mp3\n",          "track_name": "Lion City ",          "release_id": 560783,    ...

Issues encountered when running a Vue.js project that already exists

I'm encountering an issue while trying to launch a pre-built UI project using vue.js. Despite having Python installed with the environment variable properly set, I keep getting an error when running the npm install command. How can this be resolved? n ...

Angular js is a powerful framework that allows for the seamless transition of views, except for the home

I am currently using the ng-animate module to implement sliding effects for my app views. Each route has its own unique slide animation. Take a look at my simple code below: HTML: <div ng-view ng-animate class="slide"></div> CSS: /*Animatio ...