'Can't retrieve data from state using Pinia Store
I'm trying to get over the composition API and Pinia with Vue3.
I'm making a call to an external API to fetch some data and store it in the state of the store, my issue here is that when I call this state from my page, it appears to be empty and I can't retrieve the data that I've been calling in the actions section of my store. Any ideas where I'm wrong in the process?
App.vue
<template>
<h1>Rick And Morty</h1>
<ul>
<li v-for="(item, index) in characters" :key="index">
{{item}}
</li>
</ul>
</template>
<script>
import { useCharactersStore } from '@/stores/characters'
import { onBeforeMount } from 'vue'
export default {
setup() {
const useStore = useCharactersStore()
const characters = useStore.characters
console.log("Store: " + characters)
onBeforeMount(() => {
useStore.fetchCharacters()
})
return {
useStore,
characters
}
},
}
</script>
character.js
import { defineStore } from 'pinia'
export const useCharactersStore = defineStore('main', {
state: () => {
return {
characters: [],
page: 1
}
},
actions: {
async fetchCharacters() {
const res = await fetch('https://rickandmortyapi.com/api/character/')
const { results } = await res.json()
this.characters.push(results)
console.log("Back: " + this.characters)
}
}
})
Solution 1:[1]
The problem is the entire results array is inserted into characters as one element:
this.characters.push(results) // ?
To push all results into characters as individual array elements, use the spread operator (i.e., ...results):
this.characters.push(...results) // ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tony19 |
