Pinia has not been instantiated yet due to an incorrect sequence of JavaScript file execution within Vue.js

I'm currently developing a Vue.js application using Vite, and I have a Pinia store that I want to monitor. Below is the content of my store.js file:

import { defineStore } from 'pinia';

const useStore = defineStore('store', {
  state: () => ({
    currentLayout: {},
    currentPuzzle: {},
    difficulty: 2,
    solvedPuzzles: new Set(),
  }),
  actions: {
    setLayout(layout) {
      this.currentLayout = layout;
    },
    setPuzzle(puzzle) {
      this.currentPuzzle = puzzle;
    }
  }
});

export default useStore;

In order to monitor it, I attempted the following just before the export statement:

const store = useStore();
... // some vue.js watching logic

However, when I invoke useStore at this point, I encounter the error:

Uncaught Error: [🍍]: "getActivePinia()" was called but there was no active Pinia. Did you forget to install pinia?

Upon further investigation with console.logs, I discovered that the main.js file is executed after store.js, causing Pinia not to be instantiated yet. How can I resolve this issue? And what determines the execution order of these JavaScript files in a Vue.js application? I am working with Vue v3.3.4, Vite v4.3.9, and Pinia v2.1.4 (all up-to-date versions).

Answer №1

To initialize Pinia in your main.js file, you will need to import the necessary methods:

import { createPinia, setActivePinia } from 'pinia';

After importing the methods, you can proceed with the following code snippet:

const pinia = createPinia();

setActivePinia(pinia);
app.use(pinia);

If you want more information on how to instantiate Pinia outside of components, refer to this link.

It is also recommended to utilize the composition syntax for stores as it allows easy creation of watchers. You can learn about setting up stores here.

Furthermore, you can use the subscribe method to directly monitor the state of your Pinia instance by visiting this page.

I hope this information proves helpful :)

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

Adapting body designs in Nuxt/Vue layout

Struggling to apply body styles in my Nuxt template, encountering issues. Attempting to utilize the beforeCreate, but facing an error: document is not defined. Desire to maintain SSR while adding styling to the body element. How can this be achieved? < ...

Is there a way to change HTML retrieved from an AJAX request before inserting it into the document?

I am utilizing an ajax call to retrieve an HTML page from the server; the ajax call is structured as follows: function loadHtml() { $.ajax({ type : 'GET', async : false, url : &apos ...

The Distinction Between "Q" and "q" in AngularJS and RequireJS

Currently, my project involves developing a single page application using AngularJS, Breeze, and RequireJS. While trying to configure AMD with requirejs to integrate Angular and Breeze, I ran into an issue related to Breeze's dependency on "q". Intere ...

What could be causing a syntax error when I use `npm run start` with npm react-scripts?

After months of working on a full stack React app, I encountered an unexpected error when trying to run npm run start from the command line. The error message was as follows: // npm run start > [email protected] start /Users/eden/Documents/GitH ...

Navigating the landscape of asynchronous asset loading can present challenges. Attempting to access assets immediately may result in receiving

I have encountered an issue while trying to load my assets into an array using a function called LoadJSON(). This function utilizes THREE.ObjectLoader() to load JSON files. The problem arises when I attempt to access the members of the array immediately af ...

Receiving a "Bad Request" error when trying to access a website

Every time I attempt to call a lengthy URL, I encounter a Bad Request issue. https://localhost:44320/RespostaEmail/96635/750396/[%7B%22IdItem%22:8,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:1,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:3,%22IdTipoReposta%22:8 ...

In search of an improved scoring system for matching text with JavaScript

For many of my projects, I've relied on String Score to assist with sorting various lists such as names and countries. Currently, I am tackling a project where I need to match a term within a larger body of text, like an entire paragraph. Consider t ...

Update the state when a button is clicked and send a request using Axios

Currently in my front end (using react): import '../styles/TourPage.css'; import React, { Component } from 'react'; import axios from 'axios' class TourPage extends Component { constructor(props) { super(p ...

Regularly check in with the server via ajax calls

I have a page that needs to send periodic "background" ajax requests after it is loaded. These requests should be sent at specific time intervals. Would using cron be the best option for this task, considering that I have never used it before? Are there a ...

The art of bringing a pseudo class to life through animation

Seeking assistance with achieving a unique effect on click event. I have set up a slanted or razor-blade style div using a parent div element and a pseudo-element :after (as shown below). My goal is to change the skew angle when the user clicks on the pare ...

When a user clicks on a button, AJAX and jQuery work together to initiate a setInterval function that continually

Currently, I have two scripts in place. The first script is responsible for fetching a specific set of child nodes from an XML file through AJAX and using them to create a menu displayed as a list of buttons within #loadMe. What's remarkable about thi ...

"When the value is false, use the Vue binding to apply a specific

My challenge involves managing a website that is designed to receive boolean values and store them in an array where the key represents the ID and the value represents the boolean. For example: policiesActive[ "2" => false, "3" => false] The w ...

Looking for assistance with resizing and repositioning an image within a viewport?

The JSFiddle code can be found at this link - https://jsfiddle.net/pmi2018/smewua0k/211/ Javascript $('#rotate').click(function(e) { updateImage(90, 0) console.log("rotation"); }); $('#zoom-in').click(function() { updateImage(0 ...

Troubleshooting iFrame Loading Issues with HTML5 PostMessage

Our code is utilizing the newest postMessage feature in HTML 5 to address cross-domain communication challenges. The issue I am facing is figuring out how to determine if the messages posted to an iFrame have been successfully loaded. If the frame fails to ...

Strange response received from Stack Overflow API request

Having some issues with the code I'm using to call the Stack Overflow API: var request = require('request'); var url = 'http://api.stackexchange.com/2.2/search?order=desc&sort=activity&tagged=node.js&intitle=node.js&sit ...

Display a helpful tooltip when hovering over elements with the use of d3-tip.js

Is it possible to display a tooltip when hovering over existing SVG elements? In this example, the elements are created during data binding. However, in my case, the circles already exist in the DOM and I need to select them right after selectedElms.enter ...

In the production build of React with Vite v5, SCSS files are not split into multiple CSS chunks

I'm struggling to enable CSS code splitting with my .scss files using Vite. It works fine in development mode, but when I try to do a production build, I only end up with one consolidated index.css file. I've searched everywhere for a solution a ...

What is the method for extracting a value that is being displayed beneath a text in a React component using Selenium?

Attached is a screenshot showcasing HTML tags: Our task is to display the 3 within react-text. Here's the code snippet I attempted: WebElement MyText = driver.findElement(By.xpath("(//div[@class='badge-number'])[6]")); JavascriptExecut ...

employing this for the second parameter

Utilizing this.value for $(".selector") is my goal with $("#style_background") serving as my save button. However, when I implement this code, the value coming through is 'save'. How can I achieve this using dania and seablue? $("#style_backgrou ...

Using express to activate http compression

Currently experimenting with the Darksky API and came across a query parameter that caught my attention: The extend=hourly option is available. With this option, hour-by-hour data for the next 168 hours will be returned rather than just the next 48. It i ...