Pinia fails to initialize in Vue.js router

I've been experimenting with Pinia for state management in my Vue application, but I've encountered an issue where Pinia is being used before it's initialized in the main.js file.

Below is the code snippet from the routes file:

import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'

const store = useUserStore()

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/', 
      name: 'login',
      component: () => import('../views/LoginView.vue')

    },
    {
      path: '/Dash',
      name: 'dash',
      component: () => import('../views/authed/DashView.vue')
    },
    {
      path: '/Register',
      name: 'register',
      component: () => import('../views/RegisterView.vue')
    }
  ]
})

export default router

This section manages the user data in a file named user.js:

import { ref, computed, watch } from 'vue'
import { defineStore } from 'pinia'
import axios from 'axios'

// Define user data store using Pinia
export const useUserStore = defineStore('user', () => {
    const user = ref ({
        name: "",
        token: "",
        auth: false,
        
    })

    // Additional methods for setting and checking authentication status
    
    return {
        user,
        setAuth,
        checkAuth,
    }
},
{
    persist: true
})

The following code segment is from the main.js file:

import { createApp, watch } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import App from './App.vue'
import router from './router'
import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap";
import axios from 'axios'

import './assets/main.css'
const pinia = createPinia()

// Initializing Pinia and creating the app instance
const app = createApp(App)
pinia.use(piniaPluginPersistedstate)
app.use(pinia)

app.use(router, axios)

app.mount('#app')

Unfortunately, an error has been occurring. The error message reads:

Uncaught Error: [🍍]: getActivePinia was called with no active Pinia. Did you forget to install pinia?
This occurs when attempting to authenticate users for specific routes in the router file.</p>
<pre><code>import {useUserStore} from '../stores/user'

store = useUserStore()

An attempt was made to modify the main.js file based on previous suggestions, however, the error persists despite changing the import location.

import { createApp, watch } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import App from './App.vue'
import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap";
import axios from 'axios'

import './assets/main.css'
const pinia = createPinia()

const app = createApp(App)
pinia.use(piniaPluginPersistedstate)
app.use(pinia)
import router from './router'

app.use(router, axios)

app.mount('#app')

Answer №1

When you include the line import router from './router' in your main.js file, the subsequent execution of const store = useUserStore() will occur before Pinia is defined.

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

Offering a variety of choices for selecting elements in a single call while utilizing select2

I have incorporated the jQuery plugin select2 (Version 4) into my project and have applied it to all select elements using the following code: var select2_params = { minimumResultsForSearch: Infinity, templateResult: applyCategoryClasses, temp ...

Having trouble retrieving selected values from a CheckboxList in JavaScript

In my asp.net application, I have a checkbox list that is defined as follows: <asp:CheckBoxList ID="chbUserType" RepeatDirection="Horizontal" runat="server"> </asp:CheckBoxList> I have populated this checkbox list using th ...

Discovering the Modification of a Variable Value in angularJS

Within my HTML markup, I have the following input field: <input id="Search" type="text" placeholder="Search Images.." ng-model="data" ng-keypress="($event.charCode==13)? searchMore() : return"> This input field serves as a search bar for us ...

A function cannot be used with Random Song Loop

Recently delving into the world of JavaScript, I encountered a peculiar issue. When attempting to execute the following code within a function, nothing displays in the console. Yet, after testing it without the function, the expected strings appear as inte ...

Error encountered when deploying the app to the live server: 500 Internal Server Issue

I am encountering an issue with my ASP.Net web app's ajax file upload feature. While it works perfectly on my local host machine during testing, I face a 500 Internal Server error when I try to publish it to a website. The console output in Google Chr ...

"Exploring the world of Material UI styling with ReactJS: A deep dive

I've been busy developing a small web application using ReactJS and Material UI. In the documentation examples, many components include useStyles within the code. I've decided to follow suit and now have a useStyles function in each of my compone ...

Guide on concatenating the output values using jQuery

After selecting the matched records from the database, I returned to the previous page. Although I retrieved all the values, I am unsure how to append these return values on this page. What I need is to replace ROOM 2, Room 3... with the value in value.roo ...

Unable to locate property 'location' due to being undefined

When trying to use the react-router-dom 4.0.0 library, an error was encountered: Uncaught TypeError: Cannot read property 'location' of undefined The issue seems to be with browserHistory. Previously, I had been using react-router 2.x.x witho ...

Using ESLint with a Vue template stored in a standalone HTML file: A step-by-step guide

Picture having "SFC" with a template structured like this: <template src="./my-separate.html"></template> <script>/* whatever */</script> <style>/* whatever */</style> And envision a scenario where you have a functional ...

Storing arrays of objects in Laravel involves creating models, defining relationships between them,

I am in a situation where I have a form set up with specific input fields for shipping rules. The form structure is as follows: <shipping-rules-form> <div class="row" v-for="(input,index) in form.inputs" :key="index&qu ...

Guide on accessing information from a JSON array in JavaScript

Today I encountered an issue while trying to retrieve a value from a JSON array in my JavaScript code: This is the structure of the JSON array: [ { "_id": 0, "_entityMetadataList": [ { "_metadataValue": "/storage/emula ...

What are the consequences of incorporating JavaScript in PHP code for changing locations?

There is a recurring question on Stack Overflow about redirecting users in PHP after input or values have been changed, and the common suggestion is to use headers for this task. However, it's important to note that headers in PHP need to be modified ...

Looking for a way to locate any elements in jQuery that do not contain a certain CSS class?

I am looking to target all form elements that do not contain a specific CSS class. For example: <form> <div> <input type="text" class="good"/> <input type="text" class="good"/> <input type="text" class="bad"/> ...

npm update fails to update specific packages

After React was updated to version 0.15 to address the issue of excessive generation of tags, I made the decision to update my project.</p> <p>However, when I ran the command <code>npm update, it only updated to version 0.14.8. Running ...

What sets apart genuine user interactions from programmatically generated actions?

Working with webkit notifications on Chrome has presented a challenge. The window.webkitNotifications.requestPermission method must be called from a user action, such as a click. Attempting to call it at any other time will not have any effect and will not ...

Prevent Cross-Site Scripting attacks in Laravel by sanitizing user input, even when allowing HTML tags

What measures can be taken to protect against XSS attacks when a user is allowed to use HTML tags, such as in a textarea element? Avoiding the stripping or escaping of all tags complicates the situation and rules out the option of using {{ }}. It's a ...

Exploring the power of NodeJS with nested functions for conducting in-depth search

Hey there, friends! I'm currently working on a small web application using NodeJS. One of the key features in my app is a search functionality that spans across different pages. However, I have some doubts about the nested functions related to this s ...

Trouble with Live Ajax Search displaying incomplete search results

I am experiencing an issue with my HTML page that includes a text box for users to enter a country name. Once the user inputs a country, AJAX and PHP are used to query a mysql database of countries and display them in a DIV below. The code is functioning c ...

Automatically update a separate page upon adding new data in Laravel 5.8 using Ajax

I have been exploring different methods on how to automatically update another page or blade file when data is changed. Specifically, I want the data in my wintwo.blade.php to be refreshed whenever I click the Call Next button on my call.blade.php. User i ...

Ways to make an AngularJS Expression show an empty value

Consider the following HTML snippet: <p>{{ booleanVariable ? "The variable is true!" : "" }}</p> In case 'booleanVariable' evaluates to false, the expression should display nothing and the <p></p> tags should not be show ...