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

Displaying a Next.js component depending on the environment setting

Having trouble displaying a maintenance message to users based on an environment value. In my .env.local file, I have the following value set: NEXT_PUBLIC_SHOW_MAINTENANCE=true This is how my page is structured: const Index = () => { const showMai ...

JavaScript string manipulation function

Hey everyone, I need help finding a one-line solution in JavaScript to determine if a string contains a semicolon without using a loop. If anyone knows how to do this, please share your knowledge! ...

Converting a nested JavaScript array into a PHP array

Having a javascript array is how my dilemma starts: foodList = ([apple,10,],[banana,20]) To convert this to a json object and send it to php, I perform the following action: var jsonData = JSON.stringify(foodList); The challenge now is extracting values ...

Having trouble closing the phonegap application using the Back Button on an Android device

I've encountered an issue with my code for exiting the application. It works perfectly the first time, but if I navigate to other screens and then return to the screen where I want to close the app, it doesn't work. <script type="text/javascr ...

Incorporating Checkbox Value into Textbox with classic ASP and jQuery

Here is a glimpse of the code I've written: response.write "<th align=left><font size=2>" response.write "1. <input type=checkbox class='checkboxes' value='ORG'>Organization" response.write "</font> ...

Concealing my menu with overflow-x: hidden on the body is not an option

Despite setting overflow-x: hidden on the body element, I'm still experiencing horizontal scrolling and can't seem to find a solution. I've searched online for solutions without success. That's why I'm reaching out here in hopes o ...

The Express application seems to load forever after a certain period of time

I encountered a peculiar problem with my express application. It was deployed on the server and functioning properly, but after a few hours, when I tried to access the website again, it kept loading indefinitely. Below is my app.js code: const express = r ...

Generate a dynamic kendo dropdown with data sources assigned in separate methods

Creating a kendo dropdown list dynamically based on the number of received id's is presenting a challenge. A method has been implemented to loop through each id and generate a corresponding dropdown with that id. These dropdowns are not all generated ...

Upon pressing enter in the input box, the page will redirect to localhost:3000/

Utilizing the NewYorkTimes API to retrieve search queries from an input field. However, upon hitting enter after entering a query, my localhost reloads and redirects to localhost:3000/?. After using console.log(url) in the console, I confirmed that the UR ...

Utilizing a range input (slider) to extract data of importance

When dynamically adding a slider to a page using a specific string, like the one shown below: "<input type=\"range\" name=\"aName\" min=\"1\" max=\"9\"/>"; After appending it to the page with pure JavaScript, ...

What is the best way to restrict the size of a table that is filled with data from a database?

Currently using a combination of React, Node, Express, and Postgres to populate a table with data retrieved from Postgres. The issue arises when the table becomes overly long, prompting the need to display only 5 rows at once while adding a scroll bar for ...

Is it possible to transfer data from javascript to php through ajax?

I am attempting to extract the data speedMbps from my JavaScript code using Ajax to send the data to my PHP script, but unfortunately, I am not receiving any output. My experience with Ajax is limited to implementing auto-completion feature. <script sr ...

Potential Cross-Origin Resource Sharing (CORS) problem arises when integrating Node Express with an Ionic

Currently, I have an Ionic application that communicates with a Node Express application using Restangular. Everything works smoothly when the Node Express server is configured to use HTTP. On the Ionic app side: RestangularProvider.setBaseUrl('http ...

The entered value in the <input> field is not valid

I am encountering an issue where the input value is auto-filled, but when I click the submit button, the input field value is not recognized unless I modify something in it, such as deleting and adding the last word to the first name. Is there a way to m ...

User-Preferred Dark Mode Toggle Using Material-UI and Fallback Option

I am working on implementing a toggle for "dark mode" that is functioning well. However, I want the initial state to reflect the user's dark/light preference. The problem is that prefersDarkMode seems to be set to false when the page loads. It only c ...

Tips for using multiple Angular directive modules in PprodWant to enhance your Pprod experience by

Currently, I am working on jhipster Release 0.7.0 and our jhipster app has multiple types of directive modules – one for the index page and another for common directives. However, when we run the app on Prod profile, an exception occurs: [31mPhantomJ ...

Retrieving the IPv4 Address from an Express.js Request

I am currently working on setting up a whitelist for IP addresses in my API. However, when I use request.socket.remoteAddress in Express.js, I receive an IPv6 address (I believe) that looks like this: ::ffff:127.0.0.1. My main concern is how can I extract ...

The Body Parser is having trouble reading information from the form

I'm struggling to understand where I'm going wrong in this situation. My issue revolves around rendering a form using a GET request and attempting to then parse the data into a POST request to display it as JSON. app.get('/search', (re ...

Unable to integrate an if/else statement into the JSON reply

Working with an API to retrieve data and display images from it. I am attempting to implement an if/else statement that will show photos if the search term yields results in the response, and display a message indicating no results if it does not. Curren ...

The process of updating the value of an element in local storage with JavaScript

Most of the time we have an object stored in our localStorage. let car = { brand: "Tesla", model: "Model S" }; localStorage.setItem("car", JSON.stringify(car)); I am now eager to update the value of "model". How do I go about achieving this u ...