Having trouble obtaining information from the state with Pinia Store

Currently, I am delving into the world of the composition API and Pinia with Vue3.

I am facing an issue while calling an external API to fetch data and store it in the state of my store. The problem arises when I try to access this state from my page - it appears empty, and I am unable to retrieve the data that I fetched in the actions section of my store. Any insights on where I might be going wrong in this whole 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)
        }
    }
})

Answer №1

The issue lies in the fact that the entire results array is being added to characters as a single element:

this.characters.push(results) // ❌

To properly add each item from the results array into characters as individual elements, utilize the spread operator (e.g., ...results):

this.characters.push(...results) // ✅

demo

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

Displaying a blank column in a table using JavaScript

I am trying to write a JavaScript function that will add a new column to a table. I want this new column to be displayed at the index where it is added, and then hidden once the addition is complete. Here is the code for my method: function addColumnToTa ...

Creating fixed-size arrays within a Mongoose schema is a commonly sought after feature that allows

For a specific scenario where I have example input: [[1,2],[3,2],[1,3],...,[4,5]] I am wondering about the correct way to define a model schema in mongoose. Here is my initial Schema: const SubproductSchema = new Schema({ ... positions: [{ type: ...

Is there a way to detect when a user is interacting with a form item using Vue and Buefy?

I'm interested in activating an event when a user focuses on a form element created using Vue / Buefy. As a newcomer to this, I would appreciate any guidance on how to accomplish this triggering action. ...

Error 500 occurred when attempting to access an external PHP file

I am currently utilizing WP Web Scraper version 3.2. When I place the shortcode or template tag (php code) directly into my page, the plugin functions correctly and displays the values. However, when I attempt to include the template tag in an external php ...

The file field appears to be empty when sending a multipart/form-data request via AJAX

I'm encountering an issue when attempting to submit a multipart/form-data using AJAX. Here is the HTML code snippet: <form id='form_foto' method='post' enctype='multipart/form-data'> <input type='hidden ...

What is the best way to create shaded areas upon clicking them?

How can I implement shading on areas when they are clicked? Contractor Form (Package One) <area id="39" name ="39" alt="" title="39" href="#" shape="poly" coords="12,204,12,120,138,117,144,72,248,72,252,124,526,125,632,81,668,157,698,149,722,2 ...

Is it possible to add a class to a child element deep within the component hierarchy while using TransitionGroup/CSSTransition in React?

I currently have a setup like this: Parent Component: <TransitionGroup> { items.map((child, index) => { // do something return ( <CSSTransition key={index} nodeRef={items.nodeRef} timeout={1000} classNames={'item ...

Maximizing Jest's potential with multiple presets in a single configuration file/setup

Currently, the project I am working on has Jest configured and testing is functioning correctly. Here is a glimpse of the existing jest.config.js file; const ignores = [...]; const coverageIgnores = [...]; module.exports = { roots: ['<rootDir&g ...

Incorporating a JSON file through a script element

A customized I18n plugin has been developed to accept various languages through json files. The goal is to simplify usage for users by allowing them to easily insert their json package directly into a page along with the script: <script id="pop-languag ...

"Executing a query on Angular Firestore using the where clause fetches all documents from the

I am encountering a perplexing issue with my angular app that is connected to Firestore. Despite following the documentation closely, when I query for documents in a collection based on a specific condition, the array returned contains every single documen ...

How can you incorporate a custom button into the controlBar on videoJS in responsive mode?

The video player I have created using videoJS includes custom buttons in the control bar. These buttons are not clickable when viewed on mobile or tablet devices without forcing them to work. let myButton = player?.controlBar.addChild('button'); ...

Showing dynamic icons in Angular 2 applications

My goal is to dynamically load a part of my website, specifically by using icon classes defined in the interface like this: import { OpaqueToken } from "@angular/core"; import {IAppConfig} from './app.interface' export let APP_CONFIG = new Opaq ...

Issues have been raised with IE11's refusal to accept string(variable) as a parameter for the localStorage

Why is it that Internet Explorer does not recognize a string variable as a parameter for the setItem method, even though it works fine in Chrome? For example, in IE: This code snippet works: var itemName = 'anyname'; localStorage.setItem(itemN ...

The functionality of the Vueify modal seems to be malfunctioning when incorporating Vueify alongside a central Modal.vue file that houses modal templates

I've been experimenting with integrating this tutorial on creating reusable modal dialogs with Vuejs and adapting it for use with Vueify. Initially, I was able to successfully implement it, but after exploring a different approach briefly, I returned ...

How can we optimize the organization of nodes in a group?

While many questions focus on grouping nodes based on similarity, I am interested in grouping nodes simply based on their proximity. I have a vast collection of densely packed nodes, potentially numbering in the millions. These nodes take up space on-scre ...

Problems arise with contextBridge methods not functioning properly within a child window

I am currently developing with the Quasar framework. I have encountered an issue where I am unable to call myWindowAPI code in child windows. Do you know why this might be happening? In my electron-preload.ts file, I have the following code snippet: funct ...

An error occurred: Reaching the maximum call stack size when utilizing the .map function in jQuery

Encountering a console error: Uncaught RangeError: Maximum call stack size exceeded This is the jQuery snippet causing trouble: $(document).on("change","select.task_activity", function(){ selected_activity = $("select.task_activity :selected").map(fu ...

Upload a JSON file to a server using a JavaScript app

I am in the process of creating a basic JavaScript application that allows users to annotate images stored on their machine and save these annotations as a JSON file. This application is lightweight and straightforward, not requiring an app server. Howeve ...

Conditionally render a div in React with Next.js depending on the value of a prop

Struggling with an issue in my app and seeking some guidance. The problem arises when dealing with data from contentful that has been passed as props to a component. Specifically, I only want to render a particular piece of data if it actually contains a v ...

Creating form components in a row

I'm currently working on an app and I'm attempting to align 3 form elements in a ratio of 25/25/50, but it's proving to be quite challenging. At the end of this message, you'll find a picture showing the current layout. Additionally, I& ...