Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
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)
        }
    }
})
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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) // ✅

demo

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!