Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda