Having trouble retrieving Pinia data using the Composition API after a page reload? I'm utilizing Vue to parse fetched JSON data. Despite being new to the Composition API, I can't pinpoint what's causing the issue even after going through the documentation.
In this scenario, there are two components: "Template" and "Setup" drawing data from the same Pinia store that was initially loaded via an asynchronous call in App.vue
. While "Template" successfully loads data directly from the template, "Setup" struggles to access the data through Component API ref()
.
Upon the initial app load, both components display correctly. However, when the page is reloaded or navigated away and back again, only "Template" persists while "Setup" disappears. The Dev tools show that the store contains all the necessary data and functions properly.
It seems like the disappearance of "Setup" might be due to a race condition where the async data fills up before the setup function can retrieve it. This behavior is peculiar because the data eventually exists, and everything appears to be reactive as far as I can tell. The route/path and template do not seem to be causing the problem.
I've experimented with various lifecycle hooks without any success. Any insights on what could be the issue?
<script setup>
import { ref } from 'vue'
import { useProfileStore } from '@/stores/profile'
const store = useProfileStore()
import { useRoute } from 'vue-router'
const route = useRoute()
const profile = ref()
profile.value = store.getProfileBySlug(route.params.slug)
</script>
<template>
<div class="record">
<ul>
<li><h2>Template</h2><p>{{ store.getProfileBySlug(route.params.slug) }}</p></li>
<li><h2>Setup</h2><p>{{ profile }}</p></li>
</ul>
</div>
</template>
The store code snippet looks something like this:
// ... sections omitted for brevity
import { defineStore } from 'pinia'
export const useProfileStore = defineStore('profile_store', {
state: () => ({
profiles: [],
// ...
}),
getters: {
profilesSorted: (state) => {
// ... sorting logic
},
getProfileBySlug: (state) => {
return (slug) => state.profiles.find((profile) => profile.slug === slug)
},
},
actions: {
async initData() {
// defining URL options and transformation structure
const url_options = {
perPage: 100,
fields: [
'slug',
// ... other fields
]
}
// object defining sources, URLs, and structures
const models = {
profiles: {
main_url: '...',
local_url: 'http://localhost:5173/profiles.json',
url_options: {
perPage: 100,
fields: [
'slug',
// ... other fields
]
},
structure: (profile) => {
return {
slug: profile.slug,
// ... other fields
}
}
},
// ...
}
async function fetchAndTransform(model) {
// implementation details
}
this.profiles = await fetchAndTransform(models.profiles)
// ... additional types of data fetching
},
}
})