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)
}
}
})