"Encountering a glitch involving Vue.js 3, Pinia, and a centralized store

While using Pinia in a Vue.js 3 project, I encountered an issue. The problem arises when I attempt to load constant JSON structures from my backend using the file src/store/constants.store.ts

// @ts-check
import { defineStore } from "pinia"
import ConstantsApi from "@/api/constants"

export const useConstantsStore = defineStore("constants", {
    state: () => ({
        instanceTiers: [],
        instanceStatuses: [],
        queueStatuses: [],
        countries: [],
        areConstantsLoaded: false,
    }),
    actions: {
        async fetchConstants() {
            this.instanceTiers = await ConstantsApi.instanceTiers();
            this.instanceStatuses = await ConstantsApi.instanceStatuses();
            this.queueStatuses = await ConstantsApi.queueStatuses();
            this.countries = await ConstantsApi.countries();
            this.areConstantsLoaded = true;
        },
    },
})

This code relies on the functions defined in src/api/constants.ts

import {api} from "./api"

export default {
instanceTiers() {
return api("GET", "/instance_tiers");
},
// More API functions...
}

The core function for making API requests is located in src/api/api.ts, where authorization details are stored:

import {APISettings} from './config';
import {useAuthStore} from "@/stores";
import {useNotificationStore} from '@/stores';

const authStore = useAuthStore();

const notificationStore = useNotificationStore();

// Function for handling API requests
export function api(method: string, url: string, data?: any): Promise<any> {
// API request logic here
}

Authorization credentials are stored in src/store/auth.store.ts:

// @ts-check
import { defineStore } from "pinia"

export const useAuthStore = defineStore("auth", {
state: () => ({
token: JSON.parse(localStorage.getItem("token")) as string,
idToken: JSON.parse(localStorage.getItem("idToken-parsed")),
logoutUrl: localStorage.getItem("logout-url") as string,
loginUrl: localStorage.getItem("login-url") as string,
}),
getters: {
getToken: (state) => {
return state.token
},
// More getters...
},
actions: {
logout() {
// Logout action logic here
},
},
})

A central store index file src/stores/index.ts is also present in the project:

export * from "./auth.store";
// More store exports...

import { createPinia } from "pinia";

export const pinia = createPinia();

An error message "Uncaught Error: [🍍]: getActivePinia was called with no active Pinia. Did you forget to install pinia?" occurs when loading a page.

In my src/main.ts file, I have set up Pinia like this:

import { createApp } from "vue"
import { pinia } from "./stores"
import App from "./App.vue"
import { router } from "./router";
import "./assets/main.css"

const app = createApp(App);
app.use(pinia);
app.use(router);
app.mount("#app");

Changing the content of src/stores/constants.store.ts seems to resolve the issue:

// @ts-check
import { defineStore } from "pinia"

export const useConstantsStore = defineStore("constants", {
state: () => ({
instanceTiers: [],
instanceStatuses: [],
queueStatuses: [],
countries: [],
areConstantsLoaded: false,
}),
actions: {
async fetchConstants() {
this.instanceTiers = [];
this.instanceStatuses = [];
this.queueStatuses = [];
this.countries = [];
this.areConstantsLoaded = true;
},
},
})

Answer №1

Don't forget to initialize Pinia's instance using the createPinia function.

Your code should look something like this:

import { createApp } from "vue"
import { createPinia } from 'pinia'
import App from "./App.vue"
import { router } from "./router"
import "./assets/main.css"

const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.use(router);
app.mount("#app");

Answer №2

useAuthStore should not be used at the top of a module as it goes against the intended purpose of having a getter function for a store. When utilizing useAuthStore outside of a component, it is recommended to call it where the store is actually being used to avoid premature store instantiation, typically inside api:

import {APISettings} from './config';
import {useAuthStore, useNotificationStore} from '@/stores';

export function api(method: string, url: string): Promise<any>;
export function api(method: string, url: string, data: any): Promise<any>;
export function api(method: string, url: string, data?: any): Promise<any> {
export function api(method: string, url: string, data?: any): Promise<any> {
  const authStore = useAuthStore();
  const notificationStore = useNotificationStore();
  ...

In addition, src/api/constants.ts appears to serve no purpose as an abstraction and this code could be more appropriately placed within store actions.

If src/main.ts does not match the expected structure, it may indicate that Pinia has not been initialized correctly and referencing another answer could also provide clarification.

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

Load the iframe element only when the specified class becomes visible within the container div, without relying on jQuery

I am facing a unique challenge where the performance of my page is significantly impacted by loading multiple iframes. These iframes are contained within popup modals, and I would like to delay their loading until a user clicks on the modal. When the mod ...

The initial return value of $(document).height may be inaccurate, but is accurate upon recalculation

I am working on implementing a pop-up screen and I would like to darken the background when it opens. Below is the Javascript code: $(document).on('click', '.item', function(){ $("#popUp").css("display" , "block"); ...

Guidelines on Implementing a Three-Level Jquery Accordion Menu

Here is a snippet of jQuery code that I am working with: $(document).ready(function(){ $("#accordion2 h3").click(function(){ //slide up all the link lists $("#accordion2 ul ul").slideUp(); //slide down the link list below the h3 clicked - only ...

Automatically insert nested object keys and values from jQuery into their respective div elements

Below is a sample object that I am working with: "experience": { "1": { "jobtitle": "job_title", "companyname": "company_name", "companytown": "company_town", "companycountry": "company_country", "summary": "Sum ...

Is it possible for me to verify if the route I am currently on is included in a specific list of routes

Can this be made more generic? watch: { $route(to, from) { if(this.$route.path === '/home'){do something with id 1} if(this.$route.path === '/'){do it not - its not in the array} if(this.$route.path === '/about&ap ...

What causes a ReactJS component to disappear upon page refresh?

After the user clicks the Login button in the Instructor Login Form, I want to display the Instructor Profile component. Everything functions properly until I refresh the page, at which point the User Profile component disappears. Here is a screenshot of ...

Disable the button until all input fields contain text in ASP

Curious if anyone knows how to disable a button until all text boxes have input in ASP.NET and C#. Here is an image showing the scenario I'm referring to - wanting to gray out the commit button. Thanks, Chris! ...

The toggling feature seems to be malfunctioning as the div section fails to display

I'm facing an issue with my Django project while working on a template. I want to toggle the visibility of a div element between hiding and showing, but the function I used isn't working for some reason. I borrowed the function from a different t ...

It appears that the home page of next.js is not appearing properly in the Storybook

Currently, I am in the process of setting up my next home page in storybooks for the first time. Following a tutorial, I successfully created my next-app and initialized storybooks. Now, I am stuck at importing my homepage into storybooks. To achieve this, ...

existing event handler in JavaScript has already been registered on a particular plugin

Apologies for the confusing title, will make changes accordingly.. Currently, I am utilizing the Twitter Bootstrap Wizard to manage database operations. My goal is to find a way to activate the onTabShow() function by simply clicking a button. The onTabSh ...

Issue encountered with the Selenium JavaScript Chrome WebDriver

When it comes to testing an application, I always rely on using Selenium chromewebdriver. For beginners like me, the starting point was following this insightful Tutorial: https://code.google.com/p/selenium/wiki/WebDriverJs#Getting_Started After download ...

Discovering useful data like metadata and subject matter through the utilization of either a URL or the webpage itself alongside JQUery

Imagine you have a URL and you want to display information related to that URL on your webpage, similar to how Facebook or LinkedIn does. You input a URL and the website data is retrieved for display. I am working on an application using JQuery and HTML ...

Encountering difficulties when attempting to inject NotifierService into an Angular Service

I am attempting to incorporate Angular NotifierService into my service class so that I can display error notifications in case of any exceptions from the service side. I attempted to inject a bean of NotifierService in the constructor of my service class, ...

Can CSS be altered dynamically in Laravel blade?

Is there a way to dynamically change CSS? I am trying to set the class=sheet padding-top: 28mm; when the size of $anArray is less than 30. If the array has more than 30 elements then apply padding-top: 28 * 2 mm;. Finally, if the array exceeds 60, use pad ...

Discover the art of highlighting errors with React-hook-form and MUI React

My code consists of the following component: const App = () => { const formProps = useForm({ mode: "onBlur", }); const { handleSubmit, formState, register, watch, reset } = formProps; return ( <FormProvider {...formProps}> & ...

Is it possible to extract the body from the post request using req.body.item?

After working with Express, I learned how to extract body data from a post request. Most examples showed that using req.body.item should retrieve the desired value for tasks like inserting into a table. However, in my case, I found that I couldn't ac ...

How can an array of objects be sent as a query string to the endpoint URL in React?

I'm currently developing a react application and facing the challenge of dynamically constructing and appending query strings to URLs. This is necessary because I have a shared base endpoint for all links, but each link may require different parameter ...

Ways to avoid submitting based on the outcome of AJAX requests

When working on an ASP.NET MVC Project, I encountered an issue where I wanted to prevent a button from submitting if the result returned from an AJAX call was false. However, no matter what I tried, the button always triggered the submission. Below is th ...

When choosing the child option, it starts acting abnormally if the parent option is already selected in Angular

I am encountering an issue while trying to select the parent and its children in the select option. The concept is to have one select option for the parent and another for the child. I have parent objects and nested objects as children, which are subCatego ...

Attempting to update an AJAX field with the returned value, but it only updates after clicking away from it

Image of form utilizing AJAX & JS The current setup involves a maintainer that uses AJAX to update the "Calc" field in response to a number entered in the "Order No" field. The issue is that the "Calc" field does not update immediately after typing in the ...