Error: Uncaught [🍍]: The function "getActivePinia()" was invoked without an active Pinia instance present. Ensure that you have called "app.use(pinia)" before attempting to utilize a store

I encountered an issue while trying to access a store in Pinia for my Vue web application. Despite installing Pinia and setting app.use(createPinia()), I keep receiving the following error message:

Uncaught Error: [🍍]: "getActivePinia()" was called but there was no active Pinia. Are you trying to use a store before calling "app.use(pinia)"?

Here are the relevant sources:

Vue file:

<script>
import SideUpBar from "@/components/SideUpBar.vue";
import {mapActions, mapState} from "pinia"
import { useUsersStore } from "@/stores/users"

const usersStore = useUsersStore()

export default {
  name: "NewView",
  components: {SideUpBar},
  data: () => ({
    //
  }),
  computed: {
    ...mapState(useUsersStore, ['users']),
  },
  methods: {
    // ...mapActions(useUsersStore, ['fetchUsers']),
  },
  created() {
    usersStore.fetchUsers()
  },
}
</script>

<template>
  <v-layout class="dim">
    <SideUpBar/>
    <v-main style="background: #C19A6B">
      <v-list
        :items="users"
        item-title="username"
      ></v-list>
    </v-main>
  </v-layout>
</template>

<style>
.dim {
  width: 100vw;
  height: 100vh;
}
</style>


main.js:

import '@mdi/font/css/materialdesignicons.css'

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

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

// Vuetify
import 'vuetify/styles'
import { createVuetify } from 'vuetify'
import  * as components from 'vuetify/components'
import  * as directives from 'vuetify/directives'

const vuetify= createVuetify({
    components,
    directives,
})

const app = createApp(App)

app.use(createPinia())
app.use(router)
app.use(vuetify)

app.mount('#app')


users.js (store):

import {defineStore} from "pinia"

import axios from "axios";
import {ca} from "vuetify/locale";

export const useUsersStore = defineStore("user", {
    state: () => ({
        users: [],
    }),
    actions: {
        async fetchUsers() {
            try {
                const data = await axios.get('api/users')
                let users = data.data.data
                this.users = users
                console.log(data)
            } catch (e) {
                alert(e)
                console.log(e)
            }
        },
    },
})


Thank you!

Answer №1

When wrapping a store in the useUsersStore composable, the main objective is to prevent early instantiation and avoid any related race conditions. Typically, composables are meant to be called within the component setup body and contemporary lifecycle hooks such as data, created, etc. Any other usage would rely on how the composable is implemented. While Pinia composables do not have this restriction, calling them before the appropriate lifecycle stage can cause them to malfunction.

The issue arises when useUsersStore is invoked at the top level of the module. In case of using the options API, it should be done in one of the following ways:

  created() {
    useUsersStore().fetchUsers()
  },
  ...

Or:

  data: () => ({
    usersStore: useUsersStore()
  }),
  created() {
    this.usersStore.fetchUsers()
  },
  ...

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

Is there a method to store only a portion of the string object in async-storage?

Is there a way to save only part of the string object into async-storage? For example, if the "result.userPrincipalName" contains "[email protected]", I want to save only the "bob23". What is the best method to achieve this? await AsyncStorage.setIt ...

Enhance the attributes of a collection of objects using values from a different array

Looking for a way to enhance a set of objects with properties sourced from another array? I have two arrays at hand. The first one contains a series of objects, while the second one consists of integers. My goal is to attribute a new property to each objec ...

Encountering a Typescript TypeError in es2022 that is not present in es2021

I'm attempting to switch the target property in the tsconfig.json file from es2015 to es2022, but I am encountering an error while running tests that seem to only use tsc without babel: Chrome Headless 110.0.5481.177 (Mac OS 10.15.7) TypeError: Can ...

Vue Js does not include images in the dist directory when the build process is completed

In my VueJs 3 project, I am working with a list of PNG images stored in the src/assets/pngs/ directory. Within my Vue component, I use a For loop to dynamically create the list by setting the image name as the source for the img tag. This implementation wo ...

Countdown malfunction: wrong date displayed

Utilizing the Countdownjs library in my project is resulting in an incorrect day count. Incorporating AngularJS, here is the custom directive I've implemented for the countdown: .directive('tempoPercorrido', function($interval){ ret ...

Broadcast signals to an overarching frame

I have successfully embedded a chatbot (Angular 14 app) in an iframe and now I need to determine whether the frame should be minimized so it can fit within the parent container. My goal is to send custom events to the receiving frame. let iframeCanvas = do ...

Vuetify's paginated server-side datatable does not support client-side sorting

The Challenge The issue I am facing revolves around using a server-side paginated datatable. Specifically, when utilizing the Vuetify data tables component and attempting to perform client-side sorting due to using a public API that I did not develop, the ...

Placing the IconButton within an AppBar Component using React-JS

Trying to position two IconButtons within a Toolbar, one on the right side and the other on the left side. However, both are ending up on the right side. Here's my code: <AppBar position="fixed" > <Toolbar> <Ic ...

Transforming complex mathematical equations into executable code using the node.js platform

Looking to implement a mathematical formula found at the following link: https://en.wikipedia.org/wiki/Necklace_(combinatorics)#Number_of_bracelets into node.js for calculating the total number of distinct ring sequences that can be created with n length ...

Testing the performance of MEAN applications under heavy load

As I work on developing an application using the cutting-edge MEAN stack, I have successfully deployed the initial version to a server. This application comprises of a static HTML file (along with CSS and some images) as well as numerous JavaScript files. ...

use two separate keys for grouping in JavaScript

My current approach involves using the reduce method to organize the data based on the Id of each query. var data = [ {Id: "552", valor: "50.00", Descricao: "Fraldas", }, {Id: "552", valor: "35.00", Descricao: "Creme", }, {Id: "545", valor: "2 ...

Creating a dialog form using Vuetify in a VueJS application

Using the VueJS Vuetify framework, I am faced with a task of opening a dialog form - which is imported as a component template - from another template. When the ChangeMealDialog button in Meals.vue is clicked, the Modal should pop up. Below is the configur ...

Transferring a PHP session variable to JavaScript in a separate file

I successfully imported data from a CSV file into PHP and organized it into a nested array. To ensure the data is easily accessible across different files, I stored the array as a session variable. Now, the challenge lies in accessing this session variable ...

Utilizing KnockoutJS to Apply CSS Binding Based on Dropdown Selection

Check out the live example here: http://jsfiddle.net/0gmbbv5w/ In my application, I have an object retrieved from the database that I bind to a <select> var NoticeType = function (noticeType) { this.NoticeTypeId = ko.observable(noticeType.Notic ...

Different ways to resize an image in various sizes without relying on PHP thumb

I have developed an admin panel for managing reservations of charter, yacht and other vehicles. I am looking for a solution to upload only one image per vehicle and resize it in multiple sizes without relying on the phpthumb library due to its slow loadi ...

Developing a versatile Angular2 component that has the potential to be utilized across various sections of a website

Use Case: I need to display a processing screen during asynchronous calls to keep end users informed about ongoing activities across multiple sections of the website. To achieve this, I decided to create a reusable component at the global level. Issue: As ...

The configuration for CKEditor5's placeholder feature seems to be malfunctioning

I am currently experimenting with a customized version of CKEditor 5 known as BalloonBlockEditor. Below is the custom build output that I have created: /** * @license Copyright (c) 2014-2023, CKSource Holding sp. z o.o. All rights reserved. * For licens ...

Troubleshooting issue: JSON.stringify function returning 'undefined'

Having some trouble with JSON in JavaScript. I've been using JSON.stringify without issue until now. But suddenly, when I try to use it in my application, I keep getting this error in the console (Google Chrome): Uncaught TypeError: undefined is not ...

Oops! Looks like there's an issue with the route configuration for ''. Make sure to include one of the following: component, redirectTo, children, or loadChildren in order to validate the

I've been facing an issue while setting up a project with angular routing. The project is only displaying the contents of index.html and not app.component.html. Upon inspection, I noticed that the body tag just has <app-root></app-root> in ...

Disabling the visibility of elements through a transparent sticky-top menu

I'm having an issue with my website design. I have a gradient background and a sticky-top menu on the site. The problem is that when I scroll down, the content appears through the menu, which is not ideal. I don't want to apply the same gradient ...