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

Stop users from skipping ahead in an HTML5 video

Struggling to stop a user from seeking on the video player. I've attempted to bind to the event, but it's not working as expected. Any suggestions on how to successfully prevent this action? @$('#video').bind("seeking", (e) =& ...

IE11 is throwing an error due to an unexpected quantifier in the regular expression

I have a string like SHM{GHT} and I need to extract the value from within the curly braces (GHT in this case). I used RegExp successfully to do this, but encountered an issue when testing on Internet Explorer. The page broke and I received an error message ...

Is it possible for me to determine whether a javascript file has been executed?

I am currently working with an express framework on Node.js and I have a requirement to dynamically change the value (increase or decrease) of a variable in my testing module every time the module is executed. Is there a way to determine if the file has ...

Using jquery to dynamically change audio source on click

Is there a way to dynamically change the audio src using jquery? <audio id="audio" controls="" > <source src="" type="audio/mpeg" /> </audio> <ul id="playlist"> <?php if($lists) { foreach ($lists as $list) { ?> ...

The paths specified in Node.js and Express are having difficulty finding the resource files for CSS and JavaScript

I am currently using Express to develop a basic website. Everything was running smoothly until I attempted to add the following code to handle 404 errors: app.get('/*', function(req, res) { res.render('404.ejs',{ title: ' ...

Authentication for file uploads in Angular 2 using Dropzone and passportjs

I am currently working on implementing authentication for an admin user using Express, Passport, and MySQL in a specific page. The authentication process works fine, but I am facing an issue with verifying whether the user is logged in while uploading file ...

Implementing an inline cache for <script> tags that load AJAX content

Looking for a way to cache <script src> received through AJAX requests? Currently, each call attempts to load the src via AJAX by default. However, the issue is that this script remains constant throughout the session and only needs to be re-evaluate ...

How to manually trigger the ajaxLoader feature in Tabulator version 3.5

Currently, I am working with version 3.5 of Tabulator from . When populating the table using an ajax request, a "loading icon" is displayed during the loading process. Prior to executing the ajax request for Tabulator, I perform some preliminary check op ...

Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js. To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js next.config.js module.exports = { webpack: (config, options) => { config.m ...

Tips for simulating difficult private attributes within a class during unit testing in TypeScript

Is there a way to mock the value of a hard private property in a unit test? For example, how can I expect something like expect(event.getEventHis()).toBeEqual(['a', 'b']) export class EventController { #event: []; constructor() { ...

It vanishes as soon as you move your cursor away during the animation

I created a button component with text animation, but I'm encountering an issue. When I hover over the button, the animation works smoothly. However, if I quickly move my cursor away or unhover in the middle of the animation, the text disappears unex ...

Tips for testing parallel, mocked data requests in JEST by simulating cached responses with a 500ms limit

In order to simulate parallel requests fetching data from different sources, I have implemented tests that introduce artificial latency for each request. The goal is to return a simple string with an identifying digit to determine whether the data has been ...

Attempting to generate a fresh document by duplicating the data from a specific variable

Currently attempting to generate a new csv file within a specific directory. The goal is to save the data of a variable inside the created csv file: handleRequest(req, res) { var svcReq = req.body.svcReq; var csvRecData = JSON.stringify(req.bod ...

Adding vibrant colors to the expansion panel within Material UI to enhance its visual appeal

How can I customize the color of the expansion panel in material ui when it is open? Is there a way to override this in material ui? Feel free to check out the code example at this link ...

Issue occurred: The error "Undefined offset 1" was encountered while trying to upload a file via

Every time I try to pass data into my file upload controller, I keep encountering an error message that says undefined offset: 1. function TestFileUpload() { $i=0; if(!isset($_FILES[$i]) ) { echo "No file is being uploaded"; } el ...

React JS Material UI disabled button under control

I am looking for some guidance. I am working on a feature where I need to disable a button conditionally. The idea is that if something is selected from my table, then the button should be available; otherwise, it should be disabled. MUI requires a boolean ...

Reactjs slider causes unexpected useState behavior

I created an autoplay Slider with three cards using the useEffect hook. However, the manual "previous" and "forward" buttons are not functioning correctly. The useState function is not updating values as expected, leading to unexpected changes in state. ...

Narrow down product selection by multiple categories

I'm currently in the process of working with Express and MongoDB, where I have data items structured like the following: { "_id": { "$oid": "63107332e573393f34cb4fc6" }, "title": "Eiffel tower&quo ...

Refresh all tabs in the TabContainer

I have implemented multiple tabs using dojo on a web page, and I need to refresh the current tab every 5 seconds without refreshing the entire page. You can check out the code in this fiddle: http://jsfiddle.net/5yn2hLv9/4/. Here is an example of the code ...

Is there a way to automatically restart my Gulp task when I save changes?

I have a series of Gulp tasks in version 4 that handle tasks like compiling Webpack and Sass, optimizing images, etc. These tasks are automated through a "watch" task while I am working on a project. However, when my watch task is active, saving a file tr ...