"Unlocking the Power of Pinia Store in Nuxt3: A Guide to Composables

Ever since updating to nuxt 3.4.0, it seems that using Pinia store in composeables is no longer supported.

//example composable
import { useAuthStore } from '~/store/auth-store';
const authStore = useAuthStore();

export function doSomethingWithStore() {
  return authStore.checkAuthUser;
}

As a result, you may encounter the following error message:

getActivePinia was called with no active Pinia. Did you forget to install pinia? const pinia = createPinia() app.use(pinia) This will fail in production.

Check out this StackBlitz example for reference: https://stackblitz.com/edit/broken-pinia-store-in-composeables?file=composables%2FthisBreaks.js,nuxt.config.ts

Answer №1

The reason why

const authStore = useAuthStore();
is declared outside any function like you did is because it is called at an early point in the application startup, before the Pinia instance is properly initialized inside the Vue instance.

To make it work correctly, do it this way:

import { useAuthStore } from '~/store/auth-store';

export function handleStoreData() {
  const authStore = useAuthStore();
  return authStore.checkAuthUser;
}

Here are some safe places to make Pinia calls (although not an exhaustive list):

  • within the <script setup> section
  • inline within the <template> section
  • inside a function like defineNuxtMiddleware

Answer №2

The @pinia/nuxt module was mistakenly installed in your nuxt.config.ts file. In Nuxt 3, the buildModules property has been replaced by modules. This change can be identified by the Typescript error message you receive:

// nuxt.config.ts
export default defineNuxtConfig({
  // replace buildModules by modules
  modules: ['@pinia/nuxt'],
});

Another important point to note is that you must call the useAuthStore from within the composable function to avoid trying to load the store before pinia is fully loaded. The call should occur when the file is imported, not when the composable is used.

import { useAuthStore } from '~/store/auth-store';

export function doSomethingWithStore() {
  const authStore = useAuthStore();
  return authStore.checkAuthUser;
}

For a demonstration, refer to this working stackblitz

Answer №3

If you are unfamiliar with Nuxt or its development tools, it is possible that you have only installed @pinia/nuxt if you used the dev tools during installation. Keep in mind that you must also install pinia itself. If you missed this step, be sure to install both pinia and @pinia/nuxt.

To do this, you can use one of the following commands:


pnpm install -D pinia @pinia/nuxt
# or
yarn add -D pinia @pinia/nuxt
# or
npm install -D pinia @pinia/nuxt

Here is a link to the Pinia documentation:

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

A guide on extracting XML elements containing periods using JavaScript/extJS

Issue with Dot in XML Tag I am encountering a problem with tags in an XML file I am working on. The issue arises from the presence of dots within the tags, such as <tag.state> and </tag.state>. Unfortunately, JavaScript (specifically extJS) d ...

Utilizing BEM Class Names in React

How can I utilize the Post component in a way that assigns unique classes to new and old posts following BEM recommendations? Assign a unique className to every element Avoid cascading dependencies like (.posts-new post or .posts-old post) Each component ...

Looking for a way to efficiently retrieve results by matching multiple string keywords as you go through each line of a file (fs)?

Essentially, I have multiple search strings provided by the client that need to be matched with each line in a file. If a line matches all of the inputted strings, I should add that line to the results array. However, when I run the code below, it only ret ...

How can we enhance the efficiency of this JavaScript tab completion script?

This snippet of code is designed for implementation into an AJAX Chat system to facilitate tab auto-completion of user names: var usernames = new Array(); usernames[0] = "Saladin"; usernames[1] = "Jyllaby"; usernames[2] = "CadaverKindler"; usernames[3] = ...

"Embracing AngularJS with the power of IIF

As I delve into the world of AngularJS, I've encountered some intriguing code samples like this one: (function(app) { 'use strict'; app.directive('sideBar', sideBar); function sideBar() { return { res ...

Interact with elements across multiple SVG files using HTML

I have a website that consists of three SVGs. I am now looking to connect elements in these different SVGs by drawing simple lines between them. My goal is to create a line from element1 (#element1) in svg1 to element6 in svg2. Unfortunately, I am unable ...

An irritating problem with TypeScript-ESLint: when a Promise is returned without being resolved

Check out this TypeScript snippet I've simplified to showcase a problem: import * as argon2 from "argon2"; export default async function(password:string):Promise<string> { return argon2.hash(password, { type: argon2.argon2id, ...

Vuetify's text field does not feature an underline

I am currently experimenting with vuetify's text field. The initial appearance is as follows: https://i.sstatic.net/2Md2I.png Upon focusing on it, the text field transforms into this: https://i.sstatic.net/Yb1vc.png Despite ensuring that my app is w ...

"Adjusting the position of the Icon in the Material UI ItemList to make it closer

How can I bring this icon closer to the text? I'm not sure how to do it. When I enter developer mode, it shows me this. https://i.stack.imgur.com/WzhB1.png I am uncertain about what the purplish stuff indicates. My objective is to move the icon to t ...

The alert is not displaying when making an Ajax POST request

Here is the code I'm using to delete a comment. However, after deleting the comment, I am not getting any alert for success. Can someone help me identify the issue? function DeleteComment(id) { jQuery.ajax({ url: "/Admin/Comment/ ...

Navigating between socket.io and express using while loops

Currently, I am running an express app with socket.io on my raspberry pi to control an LED panel. The panel is being driven by a while loop that updates the pixels. However, I am looking for a way to modify the parameters of this loop or even switch to a d ...

Encountering issues in the terminal during the installation of React Native

When attempting to install React Native using npm install -g expo-cli, I encountered some errors. I received several deprecation warnings for various packages: [email protected]: This package has been deprecated and now only exports makeExecutableSch ...

Tips for updating a specific section of a Django webpage using AJAX

Currently, I am in the process of launching a website using Django. One crucial application on this site is the 'forum' which facilitates discussions among users. The discussion forum can be accessed through the URL 'XXX.com/forum/roomY&apo ...

Issues arise when trying to use additional loaders with Storybook 6.x and Vue 2

Moving over to Storybook 6.4 I am working on a story that involves loading a Vue component, but I keep encountering errors: ModuleParseError: Module parse failed: Unexpected token (92:0) File was processed with these loaders: * ./node_modules/vue-docgen- ...

Embedded URL in dynamically created AJAX text

I created a search field that uses ajax/jquery to generate a list of users. Result: <li class="list-group-item"> <span class="glyphicon glyphicon-user"></span> <span class="badge addUserToGroup" data-user="{{ user.getId }}"&g ...

Is there a way to extract the data types of my model's properties from the Prisma Schema?

If we consider the following Prisma Schema example: model User { id String @id @unique @default(dbgenerated("gen_random_uuid()")) @db.Uuid email String @unique username String } Is there a way to extract t ...

Navigating from Laravel Jetstream to a Vue file using the Inertia route

I am in the process of setting up a route in Laravel Jetstream using Inertia. I want the route to be /bloglist. The Vue file can be found at /resources/js/Blog/BlogList.vue Here is the route code I am using: Route::inertia('/bloglist', 'Bl ...

If the item with the specified name is not found in the list, display an image using Vue's v-if directive

<ul class="ulItems" v-for="item in listingItems" :key="item.channels"> <li class="liItems"> {{ item.itemName }} </li> </ul> I am looking to incorporate an image in situations where th ...

Checkbox column within GridView allows users to select multiple items at once. To ensure only one item is selected at a

Currently, I am facing a challenge with dynamically binding a typed list to a GridView control within an asp.net page that is wrapped in an asp:UpdatePanel for Ajax functionality. One of the main requirements is that only one checkbox in the first column c ...

What is the process for including a new item in a JavaScript dictionary?

I'm currently learning JavaScript and I've encountered a challenge. I have a dictionary that I'd like to update whenever a button is clicked and the user enters some data in a prompt. However, for some reason, I am unable to successfully upd ...