Vue3: Pinia store data not being received

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

Answer №1

After some troubleshooting, I believe I have resolved the issue at hand, although I cannot pinpoint the exact cause.

Adjusting my setup function seemed to do the trick:

<script setup>
import { computed } from 'vue'
import { useProfileStore } from '@/stores/profile'
import { useRoute } from 'vue-router'

const route = useRoute()
const store = useProfileStore()

// const slug = computed(() => route.params.slug)
const profile = computed(() => store.getProfileBySlug(route.params.slug))
</script>

It appears there may have been a synchronization issue between vue-router and the store. Tweaking the import order possibly mitigated the problem.

Main.js:

import { createApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from './router'

const app = createApp(App)
const store = createPinia()

app.use(router)
app.use(store)

app.mount('#app')

App.vue:

<script setup>
import { useProfileStore } from '@/stores/profile'
import { RouterView } from 'vue-router'


const store = useProfileStore()
store.initData()


import AppNav from './components/AppNav.vue'
</script>

Sharing this experience in case it proves helpful for someone else in the future

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

Mongodb: Search for IDs within a nested array field

My MongoDB data structure includes user profiles with friend request information. Here's an example: { _id: "someId", profile: { username: "oliv", friendRequests: [ { fromUserId: "anId", accepted: false, created: " ...

What is the best way to retrieve scope variables from multiple directives?

I am working on a directive that represents a person with changing location attributes. My goal is to access all the locations together and plot them on a map using the angular-leaflet-directive. I'm struggling to figure out how to access these variab ...

Utilize Vue-cli 3.x to load static resources

In my vue-cli 3 project, I have organized the static assets in the public directory. When compiled and built on localhost, all assets load successfully, except for some images not appearing in the browser. Despite guyana-live-logo.png, slide-1.jpg, and 97 ...

Using Double Equal in a JavaScript For Loop

I'm struggling to comprehend why utilizing a double equals (or even a triple equals) in the condition of a for loop doesn't function as expected. Consider this example: for (i = 1; i == 5; i++){ console.log(i) } When I replace == with <= ...

What is the process for incorporating a personalized validation function into Joi?

I have a Joi schema and I am trying to incorporate a custom validator to validate data that cannot be handled by the default Joi validators. Currently, my Joi version is 16.1.7 const customValidator = (value, helpers) => { if (value === "somethi ...

Is it possible to apply the active class to the current list menu item in Mark using server-side techniques instead of client-side JS

When a menu item is clicked, I want to add the active class to that specific menu item. For example, if someone clicks on the contact page, the contact option in the menu should receive the active class. I am currently working with NodeJS and Koa. Below is ...

Is there a way to halt the rendering of variables in Django?

Is there a way to prevent Django from rendering specific template variables? The scenario is that I wanted to experiment with implementing Vue.js in a Django application, which was somewhat successful. The issue arises because both Vue.js and Django use ...

The necessary data is missing in the scope of the callback function

I'm facing an issue with a callback function's variable losing its scope. Consider the following simplified array of two objects: const search = [{socket: new WebSocket('ws://live.trade/123')}, {socket: new WebSocket( ...

Accessing variables from outside the query block in Node.js with SQLite

I'm looking to retrieve all the rows from a table and store them in an array called "arr". I need to access this stored array outside of the query section. Is there a way for me to get all the rows outside of the db.each function so that I can continu ...

Utilizing AngularJS to incorporate a global scope function within another function

I have a specific AngularJS function named editlocation that triggers a Modal window to edit three data points. Following this process, I aim to execute plotmarkers, which is utilized in another scenario of an ng-click. Despite attempting different approa ...

The Discord.js error message popped up, stating that it was unable to access the property 'then' since it was undefined

I'm currently working on implementing a mute command for my discord bot, but I'm encountering an error that says; TypeError: Cannot read property 'then' of undefined I am unsure of what is causing this issue and would greatly apprecia ...

Using getJSON to return key/value pair from local host URL in JSFiddle - A step-by-step guide

After following a tutorial on building an API using Python, Flask, SQLite, and SQLAlchemy, I have successfully tested the connection by hitting the localhost address in my browser. Now, I am curious if it is possible to test this connection and see the des ...

The issue of sluggishness in Material-UI when expanding the menu is causing delays

Watch Video Having trouble with the behavior of the Menu opening and closing similar to this example. The text seems slow to change position. Any ideas why? This is the devDependencies configuration I am using in webpack. "devDependencies": { ...

Difficulties encountered when trying to create a basic timeline using Moment JS

I'm in the process of developing a straightforward report that retrieves entries through an ajax request and I aim to organize my entries by the day of the week. My desired output would look something like this: ---------------------------------- Mon ...

Different custom background images for every individual page in Nuxt

Looking for a unique background-image for each page in my app is proving to be challenging. Currently, I have defined the background-image in style/app.scss. @import 'variables'; @import 'page_transition'; @import url('https://f ...

"Exploring the functionalities of jquery .change() specifically in the

I have a jQuery change function set up to adjust the values of another select drop down whenever the user changes the month (to display the correct number of days). Everything works perfectly in most browsers, but Firefox seems to be giving me trouble :( ...

Replace the value of Undefined with an empty string

I have been utilizing exif.js to extract metadata from the images I upload on a content management system (CMS). However, sometimes when an image does not contain any metadata, certain values may show up as "undefined". My goal is to replace these "undefin ...

What steps are needed to successfully integrate bootstrap.js, jquery, and popper.js into a project by using NPM to add Bootstrap?

I've successfully set up a project and incorporated Bootstrap via npm. However, I'm facing challenges in loading the necessary javascript files for Bootstrap components. It's important to note that I am utilizing a Vagrant Box (virtual machi ...

The res.send() method in Restify was not triggered within the callback function of an event

Currently, I am utilizing restify 2.8.4, nodejs 0.10.36, and IBM MQ Light messaging for a RPC pattern. In this setup, when the receiver has the result ready, it emits an event. The below restify POST route is supposed to capture this event along with the ...

An error was thrown due to an unexpected end of JSON input while fetching from localhost

After running the code snippet provided, I encountered an Uncaught SyntaxError: Unexpected end of JSON input. As a beginner in coding, any guidance or assistance would be greatly appreciated. Thank you. fetch('http://localhost:3000/add-user', { ...