I am using Vue 3 and Pinia, and I have a store cards.js
, like this one:
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>", // some endpoint
data: {
text: languageStore.sentence,
language: languageStore.language
}
})).data.map(token => ({
text: token.text,
pos: token.pos,
}));
console.log(this.cards) // see (*)
}
}
})
Then, inside a component, I use something like 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>
However, even though when I click in the button, console output after mofifying this.cards
(*) is:
Proxy {0: {…}, 1: {…}, 2: {…}, 3: {…}}
[[Handler]]: Object
[[Target]]: Array(4)
0: {text: 'esto', pos: 'PRON'}
1: {text: 'es', pos: 'VERB'}
length: 2
[[Prototype]]: Array(0)
[[IsRevoked]]: false
(Hence the array is being correctly generated) Inside of Vue devtools I can see the state cards
has not changed (as well as I can see it in the application).
Any help would be appreciated. Thank you.
Note: I followed this tutorial.
The answer was provided by @Phil. In the docs there is a link about not destructuring the store. The correct way was to change
const { generateCards } = useCardsStore()
to
const store = useCardsStore()
and use store.generateCards
instead of store
in the template.